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:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With