9

array_key_exists is not working for large multidimensional array. For ex

$arr = array(
    '1' => 10,
    '2' => array(
        '21' => 21,
        '22' => 22,
        '23' => array(
            'test' => 100,
            '231' => 231
        ),
    ),
    '3' => 30,
    '4' => 40
);

array_key_exists('test',$arr) returns 'false' but it works with some simple arrays.

1
  • 7
    It's working exactly in the way it's supposed to - the array $arr does not have such a key. Commented Jun 1, 2010 at 10:31

4 Answers 4

15

array_key_exists does NOT work recursive (as Matti Virkkunen already pointed out). Have a look at the PHP manual, there is the following piece of code you can use to perform a recursive search:

<?php
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;
}
Sign up to request clarification or add additional context in comments.

Comments

2

array_key_exists doesn't work on multidimensionaml arrays. if you want to do so, you have to write your own function like this:

function array_key_exists_multi($n, $arr) {
      foreach ($arr as $key=>$val) {
        if ($n===$key) {
          return $key;
        }
        if (is_array($val)) {
          if(multi_array_key_exists($n, $val)) {
            return $key . ":" . array_key_exists_multi($n, $val);
          }
        }
      }
  return false;
}

this returns false if the key isn't found or a string containing the "location" of the key in that array (like 2:23:test) if it's found.

Comments

2
$test_found = false;
array_walk_recursive($arr,
                     function($v, $k) use (&$test_found)
                     {
                         $test_found |= ($k == 'test');
                     });

This requires PHP 5.3 or later.

1 Comment

indicates error at function($v, $k) use (&$test_found) and msg is 'Parse error: syntax error, unexpected T_FUNCTION in file.php on line 28'
0

Here is another one, works on any dimension array

function findValByKey($arr , $keySearch){
    $out = null;
    if (is_array($arr)){
        if (array_key_exists($keySearch, $arr)){
            $out = $arr[$keySearch];
        }else{
            foreach ($arr as $key => $value){
                if ($out = self::findValByKey($value, $keySearch)){
                    break;
                }
            }
        }
    }
    return $out;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.