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.
As of PHP7, you can use the Null Coalesce Operator:
So you can write:
and it will use
$fooif 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:
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