Search code examples
phpstatements

Can I use nested statements without curly brackets?


While not finding a "foreachelse" in the PHP manual, I came up with my own.

Would you say the following is recommended? I am a fan of compact code, and I think it has good readability. Plus it works.

$consequences = array("You ", "will ", "burn ", "for ", "this!");

if(!empty($consequences)) foreach($consequences as $consequence) { 
    // 100 lines of code to be inserted here
    echo $consequence;
} else echo "No consequences";

Before testing this I actually thought I could not use curly brackets inside a "no curly bracket statement", but it looks like you can.

Are there any arguments for using curly brakets in this case?


Solution

  • While to you this perhaps is compact and neat, it doesn't follow the convention on how these things are written. Your code will be hard to read by other developers. While there is no absolute "standard" on how to write code, there are several conventions that are adopted by a large percentage of the world.

    One line if (something) do; statements are evil, break it into two lines even if you do not need to use curly braces:

    if (something)
      do;
    

    This not only is easier to read but makes debugging easier as a break point can be placed on the "do" line if a debugger is being used, or if stepping the code it will be clear if the expression evaluated true or not.

    In your case this would become:

    if(!empty($consequences))
      foreach($consequences as $consequence) { 
        // 100 lines of code to be inserted here
        echo $consequence;
      }
    else
      echo "No consequences";
    

    While this is not "compact" as you would call it, it is maintainable, and very easy to see the code path which is your primary objective when writing clear code that is easy to debug later.

    Also note that since PHP5.4 the array keyword is no longer required in PHP, you can use the following:

    $consequences = ["You ", "will ", "burn ", "for ", "this!"];
    

    Which is not only more "compact" but more standard inline with other languages such as C, and as such very readable.

    In short, if you are not willing to adjust your viewpoint on what is "neat" code you are going to struggle in this industry. It will be hard for others to work with you, and it will be hard for you to read code written by others.