I just came up with this little helper function:
function get(&$var, $default=null) { return isset($var) ? $var : $default; }
This not only works for dictionaries, but for all variables:
$test = array('foo'=>'bar'); get($test['foo'],'nope'); // bar get($test['baz'],'nope'); // nope get($test['spam']['eggs'],'nope'); // nope get($undefined,'nope'); // nope
Passing the previous undefined variable for each link does not raise a NOTICE error. Instead, passing $var by reference defines it and sets it to null . The default value will also be returned if the passed variable is null . Also note the implicitly generated array in the spam / egg example:
json_encode($test); // {"foo":"bar","baz":null,"spam":{"eggs":null}} $undefined===null; // true (got defined by passing it to get) isset($undefined) // false get($undefined,'nope'); // nope
Note that although $var is passed by reference, the result of get($var) will be a copy of $var , not a link. Hope this helps!
stepmuel Aug 08 '14 at 1:56 a.m. 2014-08-08 13:56
source share