Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

array_key_exists is not working

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.

like image 934
ArK Avatar asked Jun 01 '10 10:06

ArK


2 Answers

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;
}
like image 182
halfdan Avatar answered Sep 28 '22 03:09

halfdan


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.

like image 34
oezi Avatar answered Sep 28 '22 03:09

oezi