2

Let's assume we have a simple $array like the following.

$array = array(
    'a' => array(
        'b' => array(
            'c' => 'd'
        ),
        'e' => 'f'
    ),
    'g' => 'h'
);

Given an arbitrary array of $keys = array('a', 'b', 'c') and a value $value = 'i', I would like to change value of $array['a']['b']['c'] to i.

For simplicity, let's assume that elements of $keys are all valid, i.e. for any positive j, $keys[j] exists and is a child of $keys[j - 1].

I came up with a solution by passing a reference to the array and looping over keys but my implementation seems a bit ugly. Is there any straight forward way of doing this?

Pejman
  • 1,328
  • 1
  • 18
  • 26

1 Answers1

2
// current key index (starting at 0)
$i = 0;
// current array (starting with the outermost)
$t = &$array;

// continue until keys are exhausted
while ($i < count($keys) - 1) {

    // update array pointer based on current key
    $t = &$t[$keys[$i++]];
}

// update value at last key
$t[$keys[$i]] = $value;

http://sandbox.onlinephpfunctions.com/code/0598f00ab719c005a0560c18f91ab00154ba9453

dana
  • 17,267
  • 6
  • 64
  • 88