简体   繁体   中英

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 ?

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 $a ? $a : $b .

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

This test false || 0 || '' || !1 || true || 'wont get this far' false || 0 || '' || !1 || true || 'wont get this far' 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM