0

I have two arrays:

$array = [
    'application' => [
        'foo' => [
            'bar' => 1
        ]
    ]
];

$array_2 = [
    0 => 'application',
    1 => 'foo',
    2 => 'bar'
];

How can I change the value of the first array knowning that the last key in the second array is the key who's value must be changed in the first array?

As you can see the second array contains all the keys from the first array. I want to do something like:

$array[$array_2] = 2;

... I suppose I must create a for loop?


For example, if I want to change the bar key value, I must do:

$array['application']['foo']['bar'] = 2;

... but I don't know which key I must change, I only have an array containing keys, and the last key in the list is the key that's value must be changed.

2
  • "How can I change the value of the first array having only the second array that contains the first array keys." - Not sure what you're trying to achieve. Can you add the expected output to the question? Commented Feb 24, 2014 at 16:28
  • This may inspire you, but don't be afraid to write your own code, you need either a for or a recursive approach. Commented Feb 24, 2014 at 16:32

3 Answers 3

1

You could build a recursive function, or use a reference:

$result =& $array;

foreach($array_2 as $key) {
    $result =& $result[$key];
}
$result = 2;

print_r($array);
Sign up to request clarification or add additional context in comments.

1 Comment

It's just what I was looking for! Thanks!
0

This will do it, although not sure what you are trying to achieve.

$array[$array_2[0]][$array_2[1]][$array_2[2]] = 2;

1 Comment

Something like that, but more 'automatic'. Thanks anyway.
0

Recursively add the keys. This works -

function get_keys($arr, &$keys){
    $keys = array_merge($keys,array_keys($arr));
    foreach($arr as $a){
        if(is_array($a)){
            get_keys($a, $keys);
        }
    }
}
$array = Array(
    'application' => Array(
        'foo' => Array(
            'bar' => 1
        )
    )
);
$keys = Array();
get_keys($array, $keys);
var_dump($keys);

OUTPUT-

array
  0 => string 'application' (length=11)
  1 => string 'foo' (length=3)
  2 => string 'bar' (length=3)

Comments

Your Answer

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