tags:

views:

1057

answers:

3

In Ruby you can easily set a default value for a variable

x ||= "default"

The above statement will set the value of x to "default" if x is nil or false

Is there a similar shortcut in PHP or do I have to use the longer form:

$x = (isset($x))? $x : "default";

Are there any easier ways to handle this in PHP?

+1  A: 

I think your longer form is already the shortcut for php... and I wouldn't use it, because it is not good to read

Some notice: In the symfony framework most of the "get"-Methods have a second parameter to define a default value...

Jochen Hilgers
+4  A: 
isset($x) or $x = 'default';
Michał Rudnicki
That'll work as long as we don't consider false values of $x to be 'set'.
Adam Bellaire
$x === false and $x = 'default';isset($x) or $x = 'default';
Michał Rudnicki
I really like the `isset($x) or $x = 'default';` version; you ought to update your answer. :-)
Ben Blank
@Adam - that's true, but the same can be said for ruby's "||=" notation: `x = false; x ||= true; x #=> true`
rampion
+2  A: 

i wrap it in a function:

function default($value, $default) {
    return $value ? $value : $default;
}
// then use it like:
$x=default($x, 'default');

some people may not like it, but it keeps your code cleaner if your doing a crazy function call.

SeanDowney
The "problem" with wrapping it in a function call is that all the arguments get evaluated. In a = b || c, c only gets evaluated if b is falsey. This may or may not be what you want.
KaptajnKold
One would hope that you're not actually calling side-effecting methods in an assignment anyway.
Kris Nuttycombe