Last Updated: February 25, 2016
·
2.659K
· endel

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"