Search code examples
phppsr-2psr-1

Can I use the if-statement in single row according to the PSR-2?


I need to know if I'am allowed to use single row if-statements according to the PSR-2 Coding Style.

I've already read the docs but i couldn't find any information about that.

https://www.php-fig.org/psr/psr-1/

https://www.php-fig.org/psr/psr-2/

<?php

// This is fine
if ($expr)
{ 
    echo $expr;
}

// This also?
if ($expr) { echo $expr; }

?>

Solution

  • no, there is clearly said:

    "An if structure looks like the following. Note the placement of parentheses, spaces, and braces; and that else and elseif are on the same line as the closing brace from the earlier body."

    https://www.php-fig.org/psr/psr-2/#51-if-elseif-else

    So 1st variant is OK, 2nd isn't.

    P.S Actually 2nd case look OK in your example, but in case of bigger conditions, in real life it is less readable, so we need to obey singular 1st approach