Something that really would like to know but never found out are shortcuts in PHP.
I am currently coding a function with a foreach
loop with just a single statement inside. I tried to omit the curly braces as you can do in if/else control structures and it works. No errors.
foreach($var as $value)
$arr[] = $value;
Now I tried to use it the same way but putting an if/else block inside it. Again, working and no errors.
foreach($var as $value)
if(1 + 1 == 2) {
$arr[] = $value;
};
Then, I thought like "why is this working?" and omitted the closing semicolon. Still working. So I tried to use the if/else statement without curly braces inside the foreach loop and again, still working and no errors. But is the foreach loop really closed/ended right now?
foreach($var as $value)
if(1 + 1 == 2)
$arr[] = $value;
At least I omitted the closing semicolon again and (as expected) a parsing error occurred.
So my big question is: When can I omit the curly braces and in which structure/loop/function? I know that I can definitely do so in if
and else
. But what about while
, for
and foreach
?
And yes, I know that it is not safe, smart, whatever to code without curly braces and there are shorthands like $condition ? true : false;
and if: doSomething(); endif;
, endfor;
and endforeach;
. I don't wanna learn about shorthands I just want to understand the conditions about when and where it is possible to omit the curly brackets.
Question&Answers:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…