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)

Leave a Comment