Add to Favorites

Lose the brackets

For short conditional logic, you don't need the brackets!

For a simple succinct if statement, you can lose the brackets.

For example, you may have a variable that needs to be set to another value when empty. This is a pretty simple if statement:

if ( empty($var) ) {
$var = 'another value';

However, all these extra brackets can unnecessarily bulk up your code. You can simplify that if statement to

if ( empty($var) ) $var = 'another value';

or if you want it on separate lines

if ( empty($var) )
$var = 'another value';

The rule here is that without brackets, the if will execute the next statement in line and that is all, don't get confused thinking that this is done by grouping

if ( empty($var) )
$var = 'another value';
$another_var = 'yes';

The above will only set var to 'another value' when it is empty, but it will always set another_var to yes because the if only applies to the first statement afterwards.

Don't become overly "bracketless", you still need those brackets for a multi statement conditional and sometimes it is just plain easier to read/follow if you use brackets vs no brackets.


12/18/2010 12:22am
Love this post - wish it was color coded.
01/11/2011 3:13pm
now it is

Leave a comment

To leave a comment, please log in / sign up