foreach
The foreach (iterable_expression as $value) statement foreach (iterable_expression as $key => $value) statement
The first form traverses the iterable given by
The second form will additionally assign the current element's key to
the
Note that It is possible to customize object iteration.
In order to be able to directly modify array elements within the loop precede
Warning
Reference of a
It is possible to iterate a constant array's value by reference:
Some more examples to demonstrate usage:
Unpacking nested arrays with list()It is possible to iterate over an array of arrays and unpack the nested array into loop variables by providing a list as the value. For example:
The above example will output: A: 1; B: 2 A: 3; B: 4 You can provide fewer elements in the list than there are in the nested array, in which case the leftover array values will be ignored:
The above example will output: 1 3 A notice will be generated if there aren't enough array elements to fill the list:
The above example will output: Notice: Undefined offset: 2 in example.php on line 7 A: 1; B: 2; C: Notice: Undefined offset: 2 in example.php on line 7 A: 3; B: 4; C: |