Search code examples
phppythonarraysdictionarylanguage-comparisons

PHP associative array equivilent to Python dict.get()


I've been out of the PHP world for a couple years and I've recently inherited a PHP project. Something that should be fairly easy in PHP is eluding me though. In Python I can do the following:

value = some_dict.get(unknown_key, default_value)

My first guess to do the same in PHP was:

$value = $some_array[$unknown_key] || $default_value;

But $value becomes a boolean because PHP doesn't support value short-circuiting. I also get a Notice: Undefined index: the_key but I know I can suppress that by prefixing @.

Is there I way to accomplish similar behavior in PHP to Python's dict.get(key, default)? I checked PHP's list of array functions but nothing stood out to me.


Solution

  • I guess you want something along the lines of the following:

    $value = array_key_exists($unknown_key, $some_array) ? $some_array[$unknown_key] : $default_value;
    

    This checks that the key exists and returns the value, else will assign the default value that you have assigned to $default_value.