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.

dreftymac
  • 31,404
  • 26
  • 119
  • 182
Uyghur Lives Matter
  • 18,820
  • 42
  • 108
  • 144
  • try `$value = $some_array[$unknown_key] ?: $default_value;` – adamr Mar 20 '14 at 16:07
  • @adamr I like your solution the best. Post it as an answer and I'll accept it. – Uyghur Lives Matter Mar 20 '14 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. – Flimm Feb 09 '17 at 15:53

3 Answers3

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.

Luke
  • 22,826
  • 31
  • 110
  • 193
4
$value = isset($some_array[$unknown_key]) ? $some_array[$unknown_key] : $default_value;

This way you won't need to suppress warnings

steven
  • 646
  • 4
  • 8
  • 2
    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` http://stackoverflow.com/q/3210935/247696 – Flimm Feb 09 '17 at 15:55
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.

dogmatic69
  • 7,574
  • 4
  • 31
  • 49
adamr
  • 740
  • 6
  • 18