Last Updated: February 25, 2016
·
521
· darhazer

default value for a variable

There's languages where you can assign default value via simple or operator. For example in JavaScript:

var a = 0 || 3;

will assign 3 to the variable. Such construct will assign boolean true in PHP.

You still can get default value on 1 line, using the fact that or has lower precedence than assignment.

$a = 0 or $a = 3;

which in a real-case scenario can look like:

$a = $b or $a = $c; // pick the first non-empty value

or

$a = some_call() or $a = $default;

2 Responses
Add your response

Very useful, thank you.

over 1 year ago ·

@blainesch put a simple method using ternary operator:
https://coderwall.com/p/h5t7rq
$foo = $bar ?: $baz ?: $quz;

over 1 year ago ·