PHP best practice: always wrap conditional statement in closing brackets

This has caught me today, so I thought I’d write this down here so it’d stuck in my head.

Check out this code:

$p = ‘abcd’.($b)?‘e’:‘f’;

What would $p be if $b is true and what would it be if $b is false?

The answer is $p will always be equal ‘e’! This is because ‘abcd’.($b) will always evaluate to true. The above code is equal to:

if ( ‘abcd’.($b) ) $p = ‘e’; else $p = ‘f’;

The code should have been written as:

$p = ‘abcd’.(($b)?‘e’:‘f’);

(e.g.: with extra brackets to separate the conditional statement from the string concatenation).

Now, some people do not like to use the above conditional syntax. My own opinion is that it is okay to use, because it can make code shorter and easier to read, which is good, right? But do not use it for complex conditional statement, ever!

// Okay:
$a = (($b) ? 1: 2);

// Longer version of the above code
// when you have few of these, your code
// would be considerably longer
if ($b) {
  $a = 1;
} else {
  $a = 2;
}

// Not okay:
$a = (($obj->dontDo()) ? $c->this() : $x = (($b)?1:2));

Happy coding!

This entry was posted in PHP and tagged , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*