Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 712
Uyghur Lives Matter Avatar asked Mar 20 '14 16:03

Uyghur Lives Matter


People also ask

Does PHP have dictionary?

There are no dictionaries in php, but PHP array's can behave similarly to dictionaries in other languages because they have both an index and a key (in contrast to Dictionaries in other languages, which only have keys and no index).

What is associative array in Python?

Associative arrays consist - like dictionaries of (key, value) pairs, such that each possible key appears at most once in the collection. Any key of the dictionary is associated (or mapped) to a value. The values of a dictionary can be any type of Python data. So, dictionaries are unordered key-value-pairs.

Are dictionaries like arrays?

A dictionary is very similar to an array. Whereas an array maps the index to the value, a dictionary maps the key to the value.

What is the difference between a list and a dict in Python?

Both of these are tools used in the Python language, but there is a crucial difference between List and Dictionary in Python. A list refers to a collection of various index value pairs like that in the case of an array in C++. A dictionary refers to a hashed structure of various pairs of keys and values.


1 Answers

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.

like image 128
Luke Avatar answered Oct 27 '22 00:10

Luke