Chaim
Chaim

Reputation: 2149

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?

Upvotes: 6

Views: 1534

Answers (4)

Your Common Sense
Your Common Sense

Reputation: 157839

with 5.3 or without 5.3 I would write.

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

because I hate write-only constructs.

Upvotes: 0

mario
mario

Reputation: 145482

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.)

Upvotes: 1

vsushkov
vsushkov

Reputation: 2435

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

Upvotes: 19

dmitry
dmitry

Reputation: 5039

$var = $value or $var = $default;

Upvotes: 5

Related Questions