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?
I just came up with this little helper function:
Not only does this work for dictionaries, but for all kind of variables:
Passing a previously undefined variable per reference doesn't cause a
NOTICE
error. Instead, passing$var
by reference will define it and set it tonull
. The default value will also be returned if the passed variable isnull
. Also note the implicitly generated array in the spam/eggs example:Note that even though
$var
is passed by reference, the result ofget($var)
will be a copy of$var
, not a reference. I hope this helps!use error control operator @ with PHP 5.3 shortcut version of ternary operator
$bar = @$foo['bar'] ?: 'defaultvalue';
I find it useful to create a function like so:
And use it like this:
The default value in this case is
null
, but you may set it to whatever you need.I hope it is useful.
If you enumerate the default values by key in an array, it can be done this way:
Which results in:
The more key/value pairs that you enumerate defaults for, the better the code-golf becomes.
Time passes and PHP is evolving. PHP7 now supports Null coalescing operator:
PHP 5.3 has a shortcut version of ternary operator:
which is basically
Otherwise, no, there's no shorter method.