One issue I had recently was that I wanted to try to get a value from an array in PHP, and if it didn't exist, I wanted to get a default value. Because I'm a very smart person, instead of spending 30 seconds programming this the obvious way, I spent 2 minutes Googling how to do it the "correct" way then another few minutes figuring out why things were suddenly not working anymore when I used a null coalescing operator (??
).
Essentially, if you do this:
$value = $my_array['key'] ?? $default;
It looks like it does the same thing it does in Javascript:
const value = my_object['key'] ?? default;
But it doesn't.
Despite the similar syntax, what happens in PHP is different from what happens in Javascript when you use ??
.
In PHP, if $my_array['key']
is undefined, $value
will be $default
. This makes sense and it's what we want.
HOWEVER, if $my_array
is undefined, $value
will also be $default
, which is totally not what we want!
This means that if you spelled $my_array
wrong, e.g. $my_arrya
, PHP won't complain about it, and you'll be left wondering why your code is always using the default value even though you have set everything right.
In Javascript, my_object['key']
will error if my_object
is undefined
. The only thing that ??
does in Javascript is check if a value is null
or undefined
, it doesn't magically hide errors that would come from having undefined variables.
In Python, you can just do this:
value = my_dict.get('key', default_value)
By the way, the solution to solving this in PHP, if you really need to get a bunch of values, is to simply code your own default getter utility.
function get_array_key_or_default(array $array, string $key, mixed $default) {
if(array_key_exists($key, $array)) {
return $array[$key];
} else {
return $default;
}
}
Leave a Reply