Pigeon Pigeon - 1 year ago 60
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:


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 Source

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'
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download