Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
356 views
in Technique[技术] by (71.8m points)

php - Check if a "run-time" multidimensional array key exists

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

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

1 Reply

0 votes
by (71.8m points)
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');

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...