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.
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).
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.
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With