PSR-2 standard for long if-conditions

user3631654 picture user3631654 · May 20, 2014 · Viewed 37.3k times · Source

I did not find any standard for this case:

if ($a == $b && $b == $c && $c == $d && $g == $d) {

}

or

if (($a == $b && $b == $c) && ($c == $d && $g == $d)) {

}

Imagine the var-names are longer and 80 letters are exceeded. How should I handle this? It could look like:

if (
       $a == $b
    && $b == $c
    && $c == $d
    && $g == $d
) {

    }

Answer

Nic Wortel picture Nic Wortel · May 20, 2014

There is no recommendation / convention for this case, and as Halcyon already mentioned this is a quite exceptional case.

However, there is a recommendation for a function call with a long list of parameters:

Argument lists MAY be split across multiple lines, where each subsequent line is indented once. When doing so, the first item in the list MUST be on the next line, and there MUST be only one argument per line.

<?php
$foo->bar(
    $longArgument,
    $longerArgument,
    $muchLongerArgument
);

So if I had to create an if-statement similar to your's, I'd do this:

if (
    $a == $b &&
    $b == $c &&
    $c == $d &&
    $g == $d
) {
    // do something
}

As you can see, this is almost the same as the solution you proposed yourself, but I prefer adding the && operators after the conditions.