r/PHPhelp • u/l008com • 1h ago
How to check if a multidimensional array key exists?
$smart_data['temperature']['current']
How can I check if that 2D key exists before trying to access it?
I had a whole long explanation of why I want to verify first but reddit ate the post with reddit server errors, ugh.
1
Upvotes
4
u/sltrsd 1h ago
Check it with isset() or if you need also include null values use array_key_exists()
1
u/HolyGonzo 1h ago
Usually you can use isset() which will check to see it exists AND isn't null.
If you just want to see if the key exists at all, then use array_key_exists().
If you're accessing it and want to get a default value if it doesn't exist or is null, then you can do:
That sets $current_temperature from $smart_data if it exists there, otherwise defaults to -123.
1
u/heshamh911 58m ago
array_key_exists takes one key at a time, so for a nested key you chain it, and you have to guard the parent level or PHP warns about the missing first key:
if (array_key_exists('current', $smart_data['temperature'] ?? [])) { // the key is there, and the value may be null }
isset() walks the chain by itself, so it does not warn when a level is missing:
if (isset($smart_data['temperature']['current'])) { // the key is there and the value is not null }
So the only real difference is null. isset() returns false when the value is null, array_key_exists() returns true when the key exists with a null value.
For the usual "read it or use a default" case, ?? does the same walk as isset and is what I would use:
$current = $smart_data['temperature']['current'] ?? null;
The catch is that ?? treats an existing null the same as a missing key. If "not measured yet" and "not configured" are different states for you, use the array_key_exists version with the ?? [] guard instead.
In Laravel, Arr::has($smart_data, 'temperature.current') does the same check with dot notation and is true for keys holding null, and data_get() reads with a default when a segment is missing.
1
u/Takeoded 34m ago
If you can treat
it's nullandit's undefinedas the same, it's trivial (!If you are unsure, this is what you actually want):If you need to treat
it's defined as nullasit's definedtoo, it's more difficult (this is probably not what you want):