Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP equivalent for Ruby's or-equals (foo ||=bar)?

Tags:

In PHP I often write lines like

isset($foo)? NULL : $foo = 'bar' 

In ruby there is a brilliant shortcut for that, called or equals

foo ||= 'bar' 

Does PHP have such an operator, shortcut or method call? I cannot find one, but I might have missed it.

like image 335
berkes Avatar asked Jul 29 '10 12:07

berkes


1 Answers

As of PHP7, you can use the Null Coalesce Operator:

The coalesce, or ??, operator is added, which returns the result of its first operand if it exists and is not NULL, or else its second operand.

So you can write:

$foo = $foo ?? 'bar'; 

and it will use $foo if it is set and not null or assign "bar" to $foo.

On a sidenote, the example you give with the ternary operator should really read:

$foo = isset($foo) ? $foo : 'bar'; 

A ternary operation is not a shorthand if/else control structure, but it should be used to select between two expressions depending on a third one, rather than to select two sentences or paths of execution

like image 71
Gordon Avatar answered Oct 04 '22 02:10

Gordon