Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Irfan-Ansari/9740770 to your computer and use it in GitHub Desktop.
Save Irfan-Ansari/9740770 to your computer and use it in GitHub Desktop.
Check if specific array key exists in multidimensional array - PHP
<?php
$array = array(
'21' => array(),
'24' => array(
'22' => array(),
'25' => array(
'26' => array()
)
)
);
var_dump(multiKeyExists($array, 22));
var_dump(multiKeyExists($array, 23));
function multiKeyExists( Array $array, $key ) {
if (array_key_exists($key, $array)) {
return true;
}
foreach ($array as $k=>$v) {
if (!is_array($v)) {
continue;
}
if (array_key_exists($key, $v)) {
return true;
}
}
return false;
}
Output:
bool(true)
bool(false)
@nycmitch25
Copy link

nycmitch25 commented Oct 25, 2016

Simpler version of your code (faster):
One thing, you are not accounting for a 3rd or 4th ..... dimensions right ?

function multiKeyExists( Array $array, $key ) {
    if (array_key_exists($key, $array)) return true;
    foreach ($array as $k=>$v) {
        if (!is_array($v)) continue;
        if (array_key_exists($key, $v)) return true;
    }
    return false;
}

In other words you will never find 222:

$array = array(
'21' => array(),
'24' => array(
'22' => array(),
'25' => array(
'26' => array(
'222' => array(),
)
)
)
);

function array_key_exists_r($needle, $haystack)
{
$result = array_key_exists($needle, $haystack);
if ($result) return $result;

    foreach ($haystack as $v) {
            if (is_array($v)) {
                    $result = array_key_exists_r($needle, $v);
            }
            if ($result) return $result;
    }
    return $result;

}
// does not go deep enough
var_dump(multiKeyExists($array, '222'));
var_dump(multiKeyExists($array, '23'));

/// this works
var_dump(array_key_exists_r('222',$array));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment