PHP - If/else, for, foreach, while - without curly braces? PHP - If/else, for, foreach, while - without curly braces? php php

PHP - If/else, for, foreach, while - without curly braces?


When you omit the braces it will only treat the next statement as body of the condition.

if ($x) echo 'foo';

is the same as

if ($x) { echo 'foo'; }

but remember that

if ($x)  echo 'foo';  echo 'bar';

will always print "bar"

Internally it's the other way around: if will only look at the next expression, but PHP treats everything in {} as a single "grouped" expression.

Same for the other control statements (foreach, and so on)


There are places where you can, but you never should.

Explicit is always better than implicit.

Who knows when you're going to have to go back and modify old code. It's so easy to miss that stuff and there's nothing gained by doing it.


It will work fine if you only have one argument inside!. But if you want to omit curly brace you can use colon and end.example:

if(a < 1 ) :    echo "a is less than 1";else :    echo "a is greater than 1";endif;