We’ve already covered the shorthand for
for loops in PHP. The versions for
foreach loops are very similar.
The only difference is the closing keywords. For a
while loop, the closing keyword is
endwhile, and for the
foreach loop, the closing keyword is
Our duck, duck, goose example for the
while loop becomes:
<ul> <?php $i = 0; while ($i < 2): ?> <li>Duck</li> <?php $i++; endwhile; ?> <li>Goose</li> </ul>
And the same example using
<ul> <?php $array = [0, 1]; foreach ($array as $i): ?> <li>Duck</li> <?php endforeach; ?> <li>Goose</li> </ul>
We’ve changed our shoe store example to use a
while loop with a nested
foreach loop. With this example, the disadvantage to bracket notation starts to become apparent. It’s hard to determine which closing bracket corresponds to the
while loop and which corresponds to the
To clean this up, begin by replacing the bracket notation for the
while loop with the shorthand version.
Now replace the bracket notation for the
foreach loop with the shorthand version.