In Javascript, we can conveniently get one of the various options that is offered in ||
operator. For example:
console.log('a' || '' || 0); // Yields 'a'
console.log(0 || 'b' || 'a'); // Yields 'b'
Those results above can easily be assigned to a variable like this:
let test = 'a' || '' || 0;
In PHP, though, when I try this:
$test = 'a' || '' || 0;
gives me a $test = 1
, with 1
meaning true
. Is there a way in PHP to get the literal value of the expression which caused it to yield true
?
You can use the Elvis operator for this purpose, e.g.
$test = 'a' ?: '' ?: 0;
var_dump($test);
> string(1) "a"
$test2 = 0 ?: 'b' ?: 'a';
var_dump($test2);
> string(1) "b"
There is also null coalescing operator (??) but it takes the second value only if the first is null, so e.g. 0 ?? 'a'
will take 0 because it's not null.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With