In this tutorial, you shall learn how to iterate over key-value pairs of a given array in PHP using foreach statement, with the help of example programs.
PHP – Iterate over Key-Value pairs of array using foreach
To iterate over key-value pairs of array in PHP, we can use foreach statement. During each iteration, we can access respective key and value of the associative array.
Syntax
The syntax to use foreach statement to iterate over key-value pairs of an array arr is
</>
Copy
foreach ($arr as $key => $value) {
//statement(s)
}
foreachis keyword$arris the associative arrayasis keyword$key,$valueare the key-value pair of that iteration
Example
In the following program, we will take an array arr with some key-value pairs as elements, and iterate through these key-value pairs using foreach statement.
PHP Program
</>
Copy
<?php
$arr = ["apple"=>52, "banana"=>84, "cherry"=>12];
foreach ($arr as $key => $value) {
echo $key . ' - ' . $value;
echo '<br>';
}
?>
Output

References
Conclusion
In this PHP Tutorial, we learned how to iterate over key-value pairs in an associative array using foreach statement.
