Quickest PHP equivalent of javascript `var a = var

2020-07-02 09:32发布

问题:

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 ?

回答1:

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.



回答2:

If You are using PHP 5.3 or higher see deceze's answer.

Other wise you could use nested regular ternary operators.

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

Wow thats ugly.

You could use an array of values instead;

$array = array(false,0,'',!1,'string','wont get this far'));

Now create a function which iterates over the array and returns the first true value.

function array_short_circuit_eval($vars = array()){
    foreach ($vars as $var)if($var)return $var;return null;
}

$value = array_short_circuit_eval($array);

echo $value; // string


回答3:

This test false || 0 || '' || !1 || true || 'wont get this far' will return a boolean value. It will return true if any of the values is true, that's how the OR works. It's not a ternary expression, which applies the first valid value to the receiving variable.

It returns 1 to PHP because you didn't cast the expression as a boolean.

You could do this to make the expression return a boolean value instead of an integer into your PHP variable:

$value = (bool)(false || 0 || '' || !1 || true || 'wont get this far');`

The return will be true.