Pigeon Pigeon - 3 months ago 8
PHP Question

Get to element in multi-dimensional array using an undetermined number of keys

This is a bit of weird one, but I can't get my head around it. I have a multidimensional array that has an unknown length and unknown number of dimensions. I also have an array of keys like so:

$keys = array(0, 2, 1, 0);


Now, if this array of keys had a determined size I would simply access my multidimensional array like so:

$multidimensional_array[$keys[0]][$keys[1]][$keys[2]][$keys[3]];


The problem is that it doesn't, the length of the keys array will change a lot. Does anyone know of a loop that could iterate across the keys arrays and then access the multidimensional array accordingly?

Answer

Assuming such array:

$multidimensional_array = array(
   0 => array(
       2 => array(
           1 => array(
               0 => 'value'        
           )
       )
   )
);

And these keys:

$keys = array(0, 2, 1, 0);

You can do:

$current = $multidimensional_array; 
foreach($keys as $key) {
    $current = $current[$key];
}

var_dump($current); //'value'
Comments