How to correctly format PHP 'IF ELSE' statements? How to correctly format PHP 'IF ELSE' statements? php php

How to correctly format PHP 'IF ELSE' statements?


I personally format my if/else like the last one:

if ($variable == 'setvalue') {    $variable = executefunctiononvariable($variable);} else {    $variable = executedifferentfunctiononvariable($variable);}

Your version is kind a mixture of 1 and 3, in my mind.

I have also worked with coders that do all of them and have never heard of a standard one.

The php website uses the last one: http://ca2.php.net/manual/en/control-structures.elseif.php

I also use the second example in some cases when the if statement will always be very short. If there's ever a possibiltiy of it getting longer (more than 1 line each) I'll do #1. I try to avoid #2 when possible cause it's hard to add the {} later.


I use the last one:

if ($variable == 'setvalue') {    $variable = executefunctiononvariable($variable);} else {    $variable = executedifferentfunctiononvariable($variable);}    

That being said, it is pretty unimportant which one you go with, just make sure you are consistent.


The Right Way is to follow your project's coding standard. If you don't have one, adopt one from PHP-FIG, Zend, Symfony, etc.

This form appears very popular:

if (condition) {    statements} else {    statements}

For variable assignment I'll use a ternary only if the statement can fit legibly on one line:

$variable = !empty($foo) ? $foo : 'default';

Update: I've removed the bit about a multi-line ternary statements as I no longer consider this a wise practice.