How to correctly format PHP 'IF ELSE' statements?

Question!

It's been a long running issue that I've come across in many-a-hot-and-steamy coding sessions.

One person codes this way another codes that way. So after much push and pull I'm curious... Is there any correct way of phrasing a PHP 'IF ELSE' statement?

Personally I use the:

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

After many arguments though I've been presented with other options such as:

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

OR

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

OR

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


Answers

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.



Really to me... it just doesn't matter. I believe you should be able to read either way without issues. Does it really matter if the curly brace is on a new line or not? Does it really matter if there's a space after the closing parenthesis or not?

As long as the code is done in a such way that there's been at least an attempt at making it readable, I really just don't care.

Is there a correct way? Well if there was, then why do we have options of doing it differently?



Don't forget about

if (expression):
   // code goes here
elseif (another expression):
   // code goes here
else:
   // code goes here
endif;

I personally like this structure when I'm cooking some tag soup.



This video can help you solving your question :)
By: admin