If an array $array
and keys sequence $keys = array('key1','key2','key3')
how to get $array[$keys[1]][$keys[2]][$keys[3]]
given the number of keys is unsure, there could be 4 keys, or 1 key, etc.?
My code currently is:
switch(count($keys)) {
case 1:
if(array_isset($array[$keys[0]]), $array)
$value = $array[$keys[0]];
break;
case 2:
if(array_isset($array[$keys[0]][$keys[1]]), $array[$keys[0]])
$value = $array[$keys[0]][$keys[1]];
break;
case 3:
if(array_isset($array[$keys[0]][$keys[1]][$keys[2]]), $array[$keys[0]][$keys[1]])
$value = $array[$keys[0]][$keys[1]][$keys[2]];
break;
case 4:
if(array_isset($array[$keys[0]][$keys[1]][$keys[2]][$keys[3]]), $array[$keys[0]][$keys[1]][$keys[2]])
$value = $array[$keys[0]][$keys[1]][$keys[2]][$keys[3]];
break;
default:
break;
}
function array_isset($key, Array $array) {
if(isset($array[$key])) {
return true;
}
return array_key_exists($key, $array);
}
Any better idea? I don't want to use eval
Updated, so the final code according to Alma Do Mundo
$result = $array[$keys[0]];
for($i=1;$i<count($keys);$i++) {
if(array_isset($keys[$i], $result))
$result = $result[$keys[$i]];
else {
$result = null;
break;
}
}