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;
Written by Maxim Krizhanovsky
Related protips
2 Responses
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
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Php
Authors
Related Tags
#php
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#