How to use the foreach loop with Key-Value pairs In PHP
We will use the same foreach loop to iterate over an array of key-value pairs.
Example : In this case, an array of students and their marks are taken in the array.
<?php
$markSheet = array("Ramesh"=>45, "Suresh"=>78, "Ram"=>93, "Shyam"=>69);
foreach ($markSheet as $key => $val) {
echo "$key - $val<br>";
}
?>
Output:
Ramesh - 45
Suresh - 78
Ram - 93
Shyam - 69
In the example above, we iterate over each array element and then extract the key-value pair into variables key and val respectively.
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