Joren
Joren

Reputation: 9935

Use array of keys to access multidimensional array?

For example, if I had this array:

$my_array = array('a' => array('b' => 'c'));

Is there any way to access it like this:

$my_value = access_array($my_array, array('a', 'b'));
// $my_value == 'c'

I know I could write this, but I'm curious if something like it exists in PHP already.

Upvotes: 0

Views: 50

Answers (2)

raina77ow
raina77ow

Reputation: 106483

One possible (recursive) approach:

function access_array(array $target, array $keys) {
   $target = $target[ array_shift($keys) ];
   return $keys ? access_array($target, $keys) : $target;
}

Another possible (iterative) approach:

function access_array(array $target, array $keys) {
   foreach ($keys as $k) {
     $target = $target[$k];
   }
   return $target; 
}

P.S. I can't really say it better than @MarkB did:

PHP is a toolbox. it contains screwdrivers, hammers, maybe a measuring tape and a pencil. You're expecting it to contain a fully developed house, complete with plumbing and electrical wiring for EVERY possible thing you want it to do. Instead of flailing around looking for a can opener that will cook your thanksgiving dinner and help your kids get into college, you should learn how to use the basic tools PHP does provide to BUILD that all-in-one tool.

Upvotes: 1

georg
georg

Reputation: 215039

Easy

function get_nested_key_val($ary, $keys) {
    foreach($keys as $key)
        $ary = $ary[$key];
    return $ary;
}

$my_array = array('a' => array('b' => 'c'));
print get_nested_key_val($my_array, array('a', 'b'));

For functional programming proponents

function get_nested_key_val($ary, $keys) {
    return array_reduce($keys, function($a, $k) { return $a[$k]; }, $ary);
}

Upvotes: 1

Related Questions