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?
You can use the short ternary operator in PHP 5.3+:
$d = $a ?: $b ?: $c;
Note that this does type coercion like in JS.
Update (PHP 7)
In PHP 7.0+ you would do (called null coalescing
- more informations):
$d = $a ?? $b ?? $c;
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