Chris Athanasiadis
Chris Athanasiadis

Reputation: 390

Is there a shorter syntax for the ternary operator in php?

How can I create a shorter expression of:

$variable = @$array["property"] ? $array["property"] : DEFAULT_VALUE_CONSTANT;

To something like this:

$variable = @$array["property"] || DEFAULT_VALUE_CONSTANT;

Now I get true / false

Upvotes: 1

Views: 977

Answers (1)

rray
rray

Reputation: 2556

Yes it's possible in PHP7 with Null coalescing operator (??)

$variable = $array["property"] ?? DEFAULT_VALUE_CONSTANT;

If you are using PHP version < 7 one solution is use the elvis operator

$variable = $array["property"] ?: DEFAULT_VALUE_CONSTANT;

Please avoid using @ instead of isset().

References:

?: operator (the 'Elvis operator') in PHP

Upvotes: 10

Related Questions