The Foreach Construct

The foreach construct allows you to sequentially iterate over array elements. It works with arrays and objects that implement the Traversable interface. There are two syntax variants: for iterating over values only and for iterating over keys and values.

Syntax

phpforeach (array as $value) {
  // loop body
}
phpforeach (array as $key => $value) {
  // loop body
}

Example

Simple iteration over array elements:

php<?php
  $arr = [1, 2, 3, 4, 5];
  
  foreach ($arr as $value) {
    echo $value . '<br>';
  }
?>

Code execution result:

php1
2
3
4
5

Example

Iterating over an array with getting keys and values:

php<?php
  $arr = ['a' => 1, 'b' => 2, 'c' => 3];
  
  foreach ($arr as $key => $value) {
    echo "$key: $value<br>";
  }
?>

Code execution result:

phpa: 1
b: 2
c: 3

Example

Using a reference to modify array elements:

php<?php
  $arr = [1, 2, 3, 4, 5];
  foreach ($arr as &$value) {
    $value *= 2;
  }
  
  unset($value);
  print_r($arr);
?>

Code execution result:

php[2, 4, 6, 8, 10]

See Also

  • the array_map function,
    which applies a callback function to all elements of an array
  • the array_walk function,
    which applies a user-defined function to each element of an array