0

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.

4
  • Nope, not a single-shot function. but a short recursive one to write indeed. Commented Sep 10, 2014 at 21:53
  • 1
    I really wonder how using this function is better than using bracket notation ($my_array['a']['b']). Commented Sep 10, 2014 at 21:54
  • @raina77ow: I assume because this isn't the real code, but an array of keys is provided by another process. But if the OP indeed intended to use it as-is, you have a good point. Commented Sep 10, 2014 at 21:55
  • Here's a nice listing of PHP's array functions: php.net/manual/en/ref.array.php Commented Sep 10, 2014 at 21:56

2 Answers 2

1

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);
}
Sign up to request clarification or add additional context in comments.

Comments

1

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.

2 Comments

Or, to put it shorter: batteries not included ))
I didn't want to reinvent the wheel, so I thought I'd check if it existed. After all, accessing deep stupid nested arrays feels like 90% of what I do when working with PHP. :P

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.