Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Address multi dimensional array in PHP using variable name

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?

like image 509
glutorange Avatar asked May 25 '26 00:05

glutorange


1 Answers

$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"
      }
    }
  }
}
like image 193
pNre Avatar answered May 27 '26 12:05

pNre



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!