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;
}
}
With a simple loop:
//for PHP <=5.3 replace short [] to array()
$rgData = ['key1'=>['key2'=>['key3'=>'test', 'key4'=>'data'], 'key5'=>'done']];
$rgKeys = ['key1','key2','key3'];
$rgResult = $rgData[$rgKeys[0]];
for($i=1; $i<count($rgKeys); $i++)
{
$rgResult=$rgResult[$rgKeys[$i]];
}
There could be an option with eval
, but I'd say - never use eval
- if you can avoid it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With