How to use array_keys Function to Access Keys and Values In PHP
In this new approach, we will use the array_keys function to access the keys directly and then use those keys to access the corresponding values.
Example : In this example we retrieves array keys using array_keys and iterates over them with foreach, printing each key and its corresponding value from the $markSheet array.
<?php
$markSheet = array("Nikunj" => 45, "Dhruv" => 78, "Yash" => 93, "Arti" => 69);
$keys = array_keys($markSheet); // Get all keys of the array
foreach ($keys as $key) {
echo "$key - $markSheet[$key] \n";
}
?>
Output
Nikunj - 45 Dhruv - 78 Yash - 93 Arti - 69
How to check foreach Loop Key Value in PHP ?
In PHP, the foreach loop can be used to loop over an array of elements. It can be used in many ways such as
Table of Content
- Using the for-each loop with simple values
- Using the foreach loop with Key-Value pairs
- Using array_keys Function to Access Keys and Values
Contact Us