1

Basically this is what I have

$foo = array(
    'bar' = array(
        'baz' = array(
            5
        )
    ),
);

And I have another array that holds the keys

$keys = array('bar','baz',0);

Is there a way I can get the value of the first array with the keys in the second array? I can probably try to write some recursive function that will end up getting the job done, but I was wondering if there was a neat way of doing this by using array functions ( not very good at those ) or something.. ?

Note: keys may not always be 3.

2
  • There is no other way else but using recursion Commented Aug 20, 2014 at 13:07
  • You'd need some sort of array_reduce that takes two array parameters and walks through both of them, a task too specialized to make it a built-in function. Commented Aug 20, 2014 at 13:11

2 Answers 2

3

You can try something like this, it should work

$arr = $foo;
foreach($keys as $key)
{
   $arr = $arr[$key];
}

echo $arr; // 5
Sign up to request clarification or add additional context in comments.

4 Comments

And to think that I had started writing recursive functions before I asked the question, Jesus! Thank you. Every time I convince myself that the more complicated I think a problem is, the less it actually is.
There I was, writing something complex.
Yes in that case no need to use complicated things like pure recursion
@Martijn I know that feeling.. :D
0

This could be what you are looking for. (not 100% sure if this would help)

you can see all the array functions on: http://php.net/manual/en/ref.array.php some neat ones that might do the trick:

   /function.array-fill-keys.php
   /function.array-fill.php
  /function.array-keys.php

Comments

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.