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

允我心安 提交于 2019-12-06 18:00:55

问题


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.



来源:https://stackoverflow.com/questions/36450547/quickest-php-equivalent-of-javascript-var-a-var1var2var3-expression

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!