Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP assign first not-null value

Tags:

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?

like image 629
Adam Pietrasiak Avatar asked Jul 05 '13 07:07

Adam Pietrasiak


1 Answers

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; 
like image 115
elclanrs Avatar answered Sep 19 '22 17:09

elclanrs