Alex Rivera | Logout

PHP control structures like if, else, for, foreach, while - without curly braces?

Asked 2012-01-04T11:45:38.500
64

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.

Edit
Report

3 Answers

37

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.

answered 2012-01-04T11:51:30.807
1

For single line statements.

If you tried to do

foreach($array as $x => $y)
    $do_something = $x;
    $do_something_else = $y;

Unless I am mistaken the php interpreter will take the second line under the foreach statement as being outside of the implied braces

Due to the indentation if you came back to this code at a later date, or another developer looked at your work it would be confusing.

As such it is generally wise to always use braces with these statements. It will save later headache/confusion

answered 2012-01-04T11:49:12.887
0

It's possible when you have only one expression after your clause/

For example,

foreach($var as $value)
    if(1 + 1 == 2) {
        $arr[] = $value;
    };

is correct, but

foreach($var as $value)
    $somevar = $var;
    if(1 + 1 == 2) {
        $arr[] = $value;
    };

is not, and php interpreter will think that if statement is outside foreach

answered 2012-01-04T11:48:13.387

Your Answer