javascriptphpternary-operator

Quickest PHP equivalent of javascript `var a = var1||var2||var3;` expression


Firstly is there a name for this expression ?

Javascript

var value = false || 0 || '' || !1 || 'string' || 'wont get this far';

value equals string (string) aka the fifth option

PHP

$value = false || 0 || '' || !1 || 'string' || 'wont get this far';

$value equals true (bool)

Am I right in thinking the correct way to achieve the same result as JavaScript is by nesting ternary operators? What is the best solution ?


Solution

  • The equivalent operator in PHP is ?:, which is the ternary operator without the middle part:

    $value = false ?: 0 ?: '' ?: !1 ?: 'string' ?: 'wont get this far';
    

    $a ?: $b is shorthand for $a ? $a : $b.