views:

121

answers:

5

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.

A: 

As of PHP 5.3 it's possible to use $foo ?: 'bar' Unless you expect $foo to be false

[edit]

Forget it. It still raises E_NOTICE if $foo is no set.

Mchl
It's a real pity that this feature was implemented only since php 5.3
Kirzilla
Try is isset($foo) ?: 'bar';
Paul Dragoonis
@Paul Dragoonis, nope. ?: returns the first part or the second if false. `$foo = isset($foo) ?: 'bar';` would set `$foo` to `true` if it is set, or 'bar' if it is not... It's a great oversight in ternary usage...
ircmaxell
I seen the PHP RFC wiki post for this inclusion into PHP 5.3 although i've never used it for 5.2 backwards compatability. Stick to good ol' fashion ternary :)
Paul Dragoonis
+2  A: 

No, PHP does not have an equivalent for this.

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

Gordon
the example doesn't set anything unless $foo isn't set. That's what threw me for a loop the first time i read it. there is no assignment of the expression result as a whole.
Scott M.
@Scott not sure which example you are refering to. In my example $foo will be assigned bar unless $foo already exists, in which case, it will retain it's current value.
Gordon
the first example. You are very much correct. I think we are agreeing in a very roundabout way :)
Scott M.
+1  A: 

No. According to w3schools, that operator doesn't exist.

Also, the PHP code you posted is rather cryptic. I prefer something like this:

if (!isset($foo)) $foo = 'bar';
Scott M.
My code is indeed cryptic, that is exactly why I am looking for a cleaner way :).
berkes
A: 

From the manual:

Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.

It's not exactly the same though. Hope it helps anyway.

kschaper
Mchl was faster ;)
kschaper
+2  A: 

You could create your own function:

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