3

I've been searching for hours, read http://php.net/manual/en/language.variables.variable.php with all comments but did not find a solution for my problem :(

There is a multi dimensional array, for example:

Array
(
    [53] => Array
    (
        [59] => Array
            (
                [64] => Array
                    (
                        [65] => Array
                            (
                            )
                        [66] => Array
                            (
                            )
                    )
            )
    )
[67] => Array
    (
    )
[68] => Array
    (
        [69] => Array
            (
            )
    )

)

I need to replace $foo[53][59][64][65] by another array. The "path" is available as string, i.e. "53.59.64.65" or "[53][59][64][65]".

What is the correct syntax to solve this issue?

3
  • $foo[53][59][64][65] = new_array() what does this give you ? Commented Sep 25, 2013 at 14:42
  • Didn't got it. What is your problem, get the right array according to your "path" or just replace it? Commented Sep 25, 2013 at 14:42
  • The problem is, that I need to access the original array programmatically. The "path" read from a database. So I know that the variable is named $foo and the path is [53][59][64][65] but I need to replace the contents by another array $bar. Commented Sep 25, 2013 at 14:44

1 Answer 1

3
$array = array(
    5 => array(
        6 => array(
            7 => 'Hello'
        )
    )
);

// key of the object to replace
$path = "[5][6][7]";
// gets the int values from the keys
if (preg_match_all('/\[(\d+)\]/', $path, $matches) !== false) {

    //  reference to the array
    $addr = &$array;

    //  for each key go deeper
    foreach ($matches[1] as $key) {
        $addr = &$addr[$key];
    }

    //  replace the object's value with a new array
    $addr = array(8 => 'New');
    unset($addr);

    var_dump($array);
}

The output is

array(1) {
  [5]=>
  array(1) {
    [6]=>
    array(1) {
      [7]=>
      array(1) {
        [8]=>
        string(3) "New"
      }
    }
  }
}
Sign up to request clarification or add additional context in comments.

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.