简体   繁体   中英

PHP array_key_exists and is not empty

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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM