Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting literal expression value with OR operators instead of true or false in PHP [duplicate]

Tags:

php

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?

like image 698
Richard Avatar asked Feb 25 '19 06:02

Richard


1 Answers

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.

like image 150
Karol Samborski Avatar answered Oct 13 '22 00:10

Karol Samborski