0

Following on from a previous question, I am now using the following function to check if a key exists in a multi-dimensional 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) || is_object($v))
            $result = array_key_exists_r($needle, $v);
            if ($result)
            return $result;
        }

        return $result;
    }

I am checking like this...

if (array_key_exists_r("image",$myarray)) {
echo 'Array Key Image Exists';
}

But now I am trying to modify it or the result to check that key is not empty, can I do this inside the function or should I do something with the output of the function?

Or should I be using isset instead?

fightstarr20
  • 11,682
  • 40
  • 154
  • 278

2 Answers2

1

Whether you do this inside the function or not it's fully up to you. Personally if I did it inside the function I would change its name to something clearer since it doesn't only check if a key exists. Anyhow I found a solution within the same function:

function array_key_exists_r($needle, $haystack){

    $result = array_key_exists($needle, $haystack);

    if ($result && $haystack[$needle]){
        return $result;
    }


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

            if ($result) {
                return $result;
            }
        }
    } 

    return false;
}

So basically I added a validation on your ifs and that did it also change the default return value to false just in case. I think it can still be enhanced but this does the job.

0

Try this approach instead. Easier!

function array_key_exists_r($needle, $haystack) {
   $found = [];
   array_walk_recursive($haystack, function ($key, $value) use (&$found) {
      # Collect your data here in $found
   });
   return $found;
}
Michael Niño
  • 437
  • 5
  • 19
  • The manual states this about array_walk_recursive: "You may notice that the key 'sweet' is never displayed. Any key that holds an array will not be passed to the function." – gview Jun 29 '17 at 23:13
  • In that case you should consider using recursive iterators. Try this [post](https://stackoverflow.com/questions/3975585/search-for-a-key-in-an-array-recursively) – Michael Niño Jun 29 '17 at 23:20