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

后端 未结 12 1674
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-27 05:31

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 sing

12条回答
  •  盖世英雄少女心
    2020-11-27 06:11

    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)

提交回复
热议问题