PHP: Fallback for default value
Looking around someone's else code, I've found this interesting trick to fallback default values:
php > $value = (null ?: "default");
=> string(7) "default"
php > $value = (0 ?: "default");
=> string(7) "default"
php > $value = ("" ?: "default");
=> string(7) "default"
php > $value = (true ?: "default");
=> bool(true)
To fallback from associative arrays, PHP will throw a notice, but it works as well:
php > $arr = array('a' => "something");
php > $value = $arr['b'] ?: "default";
PHP Notice: Undefined index: b in php shell code on line 1
string(7) "default"
It looks pretty better than lots of if/else:
php > $value = (null ?: "" ?: 0 ?: false ?: "default");
string(7) "default"
Written by Endel Dreyer
Related protips
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#