Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a multidimensional array. I need a function that checks if a specified key exists.

Let's take this array

$config['lib']['template']['engine'] = 'setted';

A function should return true when I call it with:

checkKey('lib','template','engine');
//> Checks if isset $config['lib']['template']['engine']

Note that my array isn't only 3 dimensional. It should be able to check even with only 1 dimension:

checkKey('genericSetting');
//> Returns false becase $c['genericSetting'] isn't setted

At the moment I am using an awful eval code, I would like to hear suggest :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
354 views
Welcome To Ask or Share your Answers For Others

1 Answer

function checkKey($array) {
  $args = func_get_args();
  for ($i = 1; $i < count($args); $i++) {
    if (!isset($array[$args[$i]]))
       return false;
    $array = &$array[$args[$i]];
  }
  return true;
}

Usage:

checkKey($config, 'lib', 'template', 'engine');
checkKey($config, 'genericSetting');

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...