1

I have a multidimensional-array called $xyz and created a a array for the keys for specifig value in this multidimensional-array. $valKeys(0: key1, 1: key2, 2: key3, 3: key4) Usually i would acess the Value with $xyz[key1][key2][key3][key4] = 'newvalue';

How can I use this array to access a specific value in $xyz?

HGA
  • 89
  • 2
  • 11

1 Answers1

0

Given your definition of $valKeys and $xyz, I think a recursive function is most appropriate:

function multi_array_key_get($multi_dim_array, $key_array, $pos=0) {
  $key_count = count($key_array)
  if ($pos < $key_count) {
    return multi_array_key_get($multi_dim_array[$key_array[$pos]], $pos+1);
  } 
  elseif ($pos == $key_count) {
    return $multi_dim_array[$key_array[$pos]];
  }
}

Call the function:

multi_array_key_get($xyz, $valKeys);

This is a bit of a draft function - you should add code to handle the cases where the array does not contain the key.

Setting the values using this function would require you to adjust the function with an additional argument- the value to set.

Philip Adler
  • 2,111
  • 17
  • 25
  • I thing I asked my question not clear enough. I have the keys and looking for a simple way to access value without using several [ ], but use a array which includes all the keys. Maybe its simple, but I have not found a solution. – HGA Feb 14 '18 at 18:55
  • @HGA do you always have the same number of keys? I don't see how my function does not fulfil your requirements. – Philip Adler Feb 14 '18 at 20:19