Adam Pietrasiak Adam Pietrasiak - 2 years ago 164
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
: 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 Source

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

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

Note that this does type coercion like in JS.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download