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

foreach ($arr as $key => $value) {
    //statement(s)
}
  • foreach is keyword
  • $arr is the associative array
  • as is keyword
  • $key, $value are the key-value pair of that iteration
ADVERTISEMENT

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

<?php
  $arr = ["apple"=>52, "banana"=>84, "cherry"=>12];
  
  foreach ($arr as $key => $value) {
    echo $key . ' - ' . $value;
    echo '<br>';
  }
?>

Output

Iterate over Key-Value pairs of Array using foreach in PHP

References

Conclusion

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