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?

1
  • 2
    I'm not sure I understand you, but if($needle == "") return false;? Commented Jun 29, 2017 at 22:09

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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;
}

2 Comments

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."
In that case you should consider using recursive iterators. Try this post

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.