

#Using foreach php with else if statement full
You can run into unwanted results where bar is printed while you don't want it to be printed and if your code is full of such statements then it will make it harder for you to read your own code and even more harder for others to read it. And example also shows you that if you write if ($x) There is nothing wrong with code, no performance or other issues and it is readable by other developers. As you can see it's fine to omit curly braces in case of if ($x) echo 'foo'. 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.Īs have said you don't wanna learn about shorthand's and accepted answer gives good example about omitting curly braces, but there is something to add. But what about while, for and foreach?Īnd 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. 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 is the foreach loop really closed/ended right now? foreach($var as $value)Īt least I omitted the closing semicolon again and (as expected) a parsing error occurred. So I tried to use the if/else statement without curly braces inside the foreach loop and again, still working and no errors. Then, I thought like "why is this working?" and omitted the closing semicolon.

Now I tried to use it the same way but putting an if/else block inside it. I tried to omit the curly braces as you can do in if/else control structures and it works. I am currently coding a function with a foreach loop with just a single statement inside. Something that really would like to know but never found out are shortcuts in PHP.
