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 only difference is to write $value once?

+4
source share
4 answers

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

+15
source
 $var = $value or $var = $default; 
+5
source

Another tricky solution (compatible with pre-5.3):

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

But it is really advisable if you have several possible values โ€‹โ€‹or default values. (Actually, it does not save typing, and not a compact alternative to syntax, just avoids mentioning $value twice.)

+1
source

with 5.3 or without 5.3 I would write.

 $var = 'default'; if ($value) $var = $value; 

because I hate write-only constructs.

0
source

All Articles