In PHP we have loop syntax that is similar to other languages. We use foreach
to enumerate the elements of a collection in order.
And with for, and while, we have more traditional loops—we can use these loops to iterate over indexes of a collection. Do-while can be used, but it is slightly more difficult.
Consider this example PHP program. We create an array of 3 strings at its start—the array is created without using the array()
keyword.
foreach
. It is important to note that each individual element is the second part, after the ampersand in the foreach
.count()
of the array is reached.count()
.do-while
. This is similar to while, but it does not check the count before entering the loop.// An array of 3 strings. $elements = ["one", "two", "three [END]"]; // Version 1: use foreach on array. foreach ($elements as &$element) { var_dump($element); } // Version 2: use for-loop over array. for ($i = 0; $i < count($elements); $i++) { var_dump($elements[$i]); } // Version 3: use while-loop over array. $i = 0; while ($i < count($elements)) { var_dump($elements[$i]); $i++; } // Version 4: use do-while loop over array. $i = 0; do { var_dump($elements[$i]); $i++; } while ($i < count($elements));string(3) "one" string(3) "two" string(11) "three [END]" string(3) "one" string(3) "two" string(11) "three [END]" string(3) "one" string(3) "two" string(11) "three [END]" string(3) "one" string(3) "two" string(11) "three [END]"
We can mutate elements in an array that we access through a foreach
loop, but we must use the ampersand character. This creates a mutable reference.
foreach
. Our array ends up with 2, 3, and 4.// Version 1: modify the array with & in foreach. $elements = array(1, 2, 3); foreach ($elements as &$element) { $element++; } var_dump($elements); // Version 2: cannot modify array without the & character. $elements = array(1, 2, 3); foreach ($elements as $element) { $element++; } var_dump($elements);array(3) { [0]=> int(2) [1]=> int(3) [2]=> &int(4) } array(3) { [0]=> int(1) [1]=> int(2) [2]=> int(3) }
It is possible to call a special generator function with a foreach
-loop. In a generator, the yield statement returns repeatedly, "yielding" many values to the loop.
function first_ten() { // This generator yields the first 10 integers. for ($i = 0; $i < 10; $i++) { yield $i; } } // Call generator in foreach. foreach (first_ten() as $value) { var_dump($value); }int(0) int(1) int(2) int(3) int(4) int(5) int(6) int(7) int(8) int(9)
The foreach
-loop is the clearest way to write a simple loop over the elements of an array. But if we have complex requirements, or need the index, for may be better.
do-while
are usually poor choices for looping over arrays. But for when no array is involved, they can be useful.For writing PHP programs, loops are almost always needed. And choosing the clearest loop is an essential skill—foreach
, with its "as" syntax, is an ideal choice.