Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 636
TarranJones Avatar asked Apr 06 '16 12:04

TarranJones


2 Answers

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.

like image 101
deceze Avatar answered Oct 21 '22 17:10

deceze


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
like image 2
TarranJones Avatar answered Oct 21 '22 18:10

TarranJones