The Problem of Curly Braces in Loops in PHP
Although you can omit curly braces in loops, I highly discourage doing so, as such code often leads to errors.
Let's look at an example. Suppose we have the following code:
<?php
for ($i = 0; $i <= 9; $i++)
echo $i; // will output numbers from 0 to 9
?>
I will make a small correction to the code above (find which one) - and it will stop working:
<?php
for ($i = 0; $i <= 9; $i++);
echo $i; // will output 10
?>
So, what did I fix?
The problem arose because I put
a semicolon after the bracket ) of
the loop. In this case, we get a so-called
loop without a body: it will simply spin
inside, and the next line will no longer
refer to it. Therefore, to avoid problems,
I always recommend using curly braces
in loops.
Tell me, what will be the result of executing the following code:
<?php
$arr = [1, 2, 3, 4, 5];
foreach ($arr as $elem);
echo $elem;
?>