Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP alternative to ternary operator

In JavaScript you can use the following code:

var = value || default;

Is there an equivalent in PHP except for the ternary operator:

$var = ($value) ? $value : $default;

The difference being only having to write $value once?

like image 579
Chaim Avatar asked Oct 26 '11 09:10

Chaim


3 Answers

Since of php 5.3 $var = $value ?: $default

like image 168
vsushkov Avatar answered Oct 26 '22 14:10

vsushkov


$var = $value or $var = $default;
like image 45
dmitry Avatar answered Oct 26 '22 13:10

dmitry


Another fiddly workaround (compatible with pre-5.3) would be:

$var = current(array_filter(array($value, $default, $default2)));

But that's really just advisable if you do have multiple possible values or defaults. (Doesn't really save on typing, not a compact syntax alternative, just avoids mentioning $value twice.)

like image 42
mario Avatar answered Oct 26 '22 13:10

mario