Checking for existing key in multi-dimensional array

Say I have a data structure like this:

array(3) {
["id"]=>
int(1)
["name"]=>
string(3) "foo"
["message"]=>
array(1) {
["action"]=>
string(3) "PUT"
}
}


Where 'message' and 'action' are both optional. To check if they're present my first attempt would be to write something like this:

if (array_key_exists('message', $array) && array_key_exists('action',$array['message'])){
}


Is there a cleaner implementation?

No, this is just the way of doing it.

Even when I'm not limited to a certain script language, I can't think of an cleaner solution?

You can just do this!

if (isset($array["message"]["action"])) { /*...*/ }  Proof: <?php error_reporting(E_ALL); ini_set('error_reporting', E_ALL); ini_set('display_errors', 1);$array = [
"id" => 1,
"name" => "foo",
"message" => [
"action" => "PUT",
],
];

var_dump(isset($array["message"]["action"])); // true$array = [
"id" => 1,
"name" => "foo"
];

var_dump(isset($array["message"]["action"])); // false  No log entries. Do note that if your value is null, then isset will also return false. You probably shouldn't be creating values with null. • This answer is also missing a ) and may cause a log entry to be generated due to not checking isset($array['message']) before dereferencing it. – Brythan Nov 1 '14 at 23:13
• @Brythan no it does not cause a log entry. But yes it is missing a ). – CMCDragonkai Nov 2 '14 at 5:10
• Sorry, I meant to point out that you'd have to crank your error reporting. It absolutely causes a log entry if you have your error reporting set for it. I've had it spam my logs with that previously. This was the default logging at one point. It may not be the default now (or your host may have dialed down error reporting), but I am absolutely sure that that situation can generate a log entry under certain configurations. – Brythan Nov 2 '14 at 5:21
• No it really doesn't I tested it with all error reporting switched on! – CMCDragonkai Nov 2 '14 at 5:29

Not clearer but probably the fastest solution:

if ((isset($array["message"]["action"]) || (array_key_exists('message',$array) && array_key_exists('action', $array['message']))) { /* ... */ }  The second check is needed because some values evaluated with isset() will result false despite the index does exist. I'm using this in a project of mine, but I'm using null as a muted state. (php 5.6) <?php function &option_select($options, $default, ...$path) {
if(!isset($path[0])) { return$options; }
$cursor = &$options;
foreach($path as$key) {
if(isset($cursor[$key])) { $cursor = &$cursor[$key]; } else { return$default; }
} return $cursor; }  It's a function that will lookup a path in a tree. echo option_select([A=>[B=>[C=>'hello world']]], 'NO?', 'A', 'B', 'C');  As you can see. I'm looping over the values over a array: path. In the beginning I'm setting a cursor as reference to a array I have to search in. Every time I find a new key, I'm setting the reference of the cursor to the current key I'm searching for. If you have xdebug and a good GUI, you can rewrite it to the algorithm you want. It's the isset($cursor[$key]) you have to change. Or inject it as a function: f($cursor, $key,$default) => (bool)

• You have provided an alternate solution but have not reviewed the code. Please add explanation about why this would be a better solution for the OP, rather than what they already have. – SirPython Aug 29 '15 at 1:45
• Because it isn't strongly typed SirPython. This way i can test it with unit tests, without making a unit test for every 'hardcoded-string'. So has to with testability and the speed i can create working code. – Roger Keulen Sep 13 '15 at 15:56

Been looking for a similar solution myself and came up with this. Works to determine if the key is set at all - and will return TRUE even if the value of the "action" key is NULL.

if (isset($array['message']) && array_key_exists('action',$array['message'])) {
/* ... */
}


If $array['message'] has no keys, the isset will return FALSE stopping the IF statement. If $array['message'] has any keys - even ones with NULL values - isset will return TRUE, allowing you to safely check if the 'action' array key exists in \$array['message'].