36

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?

0

6 Answers 6

48

As of PHP 5.3 you can use the ternary operator while omitting the middle argument:

$x = $x ?: 'default';
Sign up to request clarification or add additional context in comments.

1 Comment

A problem with this is that PHP may throw a notice about an undefined variable, and if you do it a lot it will clutter the output/logs depending on what you have the reporting level set to.
12

As of PHP 7.0, you can also use the null coalesce operator

// PHP version < 7.0, using a standard ternary
$x = (isset($_GET['y'])) ? $_GET['y'] : 'not set';
// PHP version >= 7.0
$x = $_GET['y'] ?? 'not set';

1 Comment

"syntactic sugar" indeed :) The docs state the operator can be chained: $username = $_GET['user'] ?? $_POST['user'] ?? 'nobody';
7
isset($x) or $x = 'default';

3 Comments

That'll work as long as we don't consider false values of $x to be 'set'.
$x === false and $x = 'default'; isset($x) or $x = 'default';
@Adam - that's true, but the same can be said for ruby's "||=" notation: x = false; x ||= true; x #=> true
4

As of PHP 7.4 you can write:

$x ??= "default";

This works as long as $x is null. Other "falsy" values don't count as "not set".

Comments

2

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 you're doing a crazy function call.

3 Comments

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.
One would hope that you're not actually calling side-effecting methods in an assignment anyway.
@KaptajnKold You can pass by ref, then the arguments won't be evald ;)
0

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...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.