foreach
The
foreach (iterable_expression as $value) { statement_list } foreach (iterable_expression as $key => $value) { statement_list }
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. Example #1 Common
Unpacking nested arrays
It is possible to iterate over an array of arrays and unpack the nested array
into loop variables by using either
array destructuring
via
In both of the following examples
The above example will output: A: 1; B: 2 A: 3; B: 4 When providing fewer variables than there are elements in the array, the remaining elements will be ignored. Similarly, elements can be skipped over by using a comma:
The above example will output: 1 2 3 4 5 6 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: foreach and references
It is possible to directly modify array elements within a loop by preceding
Warning
Reference to a
The above example will output: 0 => 2 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 2 ) 1 => 4 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 4 ) 2 => 6 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 6 ) 3 => 6 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 6 ) Example #2 Iterate a constant array's values by reference
|