Optionality of Braces in Loops in PHP
In loops, curly braces are not mandatory. If they are omitted, the loop will execute only one line below it.
Let's look at an example. Suppose we have a loop with curly braces:
<?php
for ($i = 0; $i <= 9; $i++) {
echo $i; // will output numbers from 0 to 9
}
?>
Let's omit the curly braces - and the result will not change:
<?php
for ($i = 0; $i <= 9; $i++)
echo $i; // will output numbers from 0 to 9
?>
Rewrite the following code without curly braces:
<?php
$arr = [1, 2, 3, 4, 5];
foreach ($arr as $elem) {
echo $elem;
}
?>