Adam Pietrasiak Adam Pietrasiak - 7 months ago 22
PHP Question

PHP assign first not-null value

I've got some three values like this:

$a = null
$b = 3;
$c = null


(I never know what will be
null
: maybe all of them, maybe none of them.)

Following so called lazy loading, I've tried to assign the first not-null value this way:

$d = $a or $b or $c;


(It is similar to JavaScript way
var d = a || b;
(it will assign b if there is no a).)

But in PHP it seems to not work.

Am I doing it wrong, or what is best and simplest way to do this?

Answer

You can use the short ternary operator in PHP 5.3+:

$d = $a ?: $b ?: $c;

Note that this does type coercion like in JS.