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

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


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


I really like the ?: operator. Unfortunately, it is not yet implemented on my production environment. So, if I were to make this look ruby-ish, I would go for something like:

isset($foo) || $foo = 'bar';

Or, if you want it even shorter (slower, and may yield unexpected results):

@$foo || $foo = 'bar';


You could create your own function:

function setIfNotSet(&$var, $value) {    if(!isset($var)) {        $var = $value;    }}