6

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.

3
  • try $value = $some_array[$unknown_key] ?: $default_value; Commented Mar 20, 2014 at 16:07
  • @adamr I like your solution the best. Post it as an answer and I'll accept it. Commented Mar 20, 2014 at 16:40
  • Note that even in Python, some_dict.get(unknown_key, default_value) is not the same as some_dict.get(unknown_key) or default_value. The first will only return default_value if the key unknown_key is not within the dictionary, whereas the latter will return default_value if the key is not found or if the value is falsey. Commented Feb 9, 2017 at 15:53

3 Answers 3

7

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.

Sign up to request clarification or add additional context in comments.

Comments

4
$value = isset($some_array[$unknown_key]) ? $some_array[$unknown_key] : $default_value;

This way you won't need to suppress warnings

1 Comment

Note that this is not exactly the same as Python's some_dict.get(unknown_key, default_value) for the case where the key is set but the value is null (or None in Python's case). This is the difference between isset and array_key_exists stackoverflow.com/q/3210935/247696
1

Try this:

$value = $some_array[$unknown_key] ?: $default_value;

This is equivalent to this line of code in Python:

value = some_dict.get(unknown_key, default_value)

Note that in the edge-case that the key exists but its value is falsey, you will get the $default_value, which may not be what you intend.

3 Comments

Note that this short hand ternary operator is only available from PHP v5.3 and above.
This will also generate an E_NOTICE-level warning.
Sorry for the multiple edits, but I think this much clearer now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.