Search code examples
phpif-statementshorthand-if

php if/else shorthand fail


Normal expression works fine, shorthand doesn't. Where am I wrong here?

if (isset($var)) $value = $var;
elseif ($str !== 'string') $value = $str;
else $value = null;
// works just fine

$value = (isset($var)) ? $var : ($str !== 'string') ? $str : null;
// only returns $value = $str

Thanks


Solution

  • Try with an extra set of brackets around the second shorthand block, $value = (isset($var)) ? $var : (($str !== 'string') ? $str : null);

    Added this side note...

    While it's fun trying to squeeze code into one line, it is often better to write it out so that it's easy to read. Your line of code is compact but takes a while to digest whereas...

    if (isset($var)) {
       $value = $var;
    }
    else if ($str !== 'string') {
       $value = $str;
    }
    else {
       $value = null;
    }
    

    ... makes it very clear what's going on - you'll thank yourself in a few months when you look back at your code :)