Is there a better PHP way for getting default value by key from array (dictionary)?

Yauhen Yakimovich picture Yauhen Yakimovich · Jul 14, 2011 · Viewed 37.2k times · Source

In Python one can do:

foo = {}
assert foo.get('bar', 'baz') == 'baz'

In PHP one can go for a trinary operator as in:

$foo = array();
assert( (isset($foo['bar'])) ? $foo['bar'] : 'baz' == 'baz' );

I am looking for a golf version. Can I do it shorter/better in PHP?

UPDATE [March 2020]:

assert($foo['bar'] ?? 'baz' == 'baz');

It seems that Null coalescing operator ?? is worth checking out today.

found in the comments below (+1)

Answer

Ivan Yarych picture Ivan Yarych · Dec 20, 2016

Time passes and PHP is evolving. PHP 7 now supports the null coalescing operator, ??:

// Fetches the value of $_GET['user'] and returns 'nobody'
// if it does not exist.
$username = $_GET['user'] ?? 'nobody';
// This is equivalent to:
$username = isset($_GET['user']) ? $_GET['user'] : 'nobody';

// Coalescing can be chained: this will return the first
// defined value out of $_GET['user'], $_POST['user'], and
// 'nobody'.
$username = $_GET['user'] ?? $_POST['user'] ?? 'nobody';