1

Could someone explain me, why this code works properly without crashing initial array structure?

function setArrayValueByPath($path, $value, &$array)
{
    foreach ($path as $p) {
        $array = &$array[$p];
    }
    $array = $value;
    return true;
}

$array = [
    'a' => 'v1',
    'b' => 'v2',
];
setArrayValueByPath(['hello', 'world'], '!!!', $array);

echo '<pre>';
print_r($array);
echo '</pre>';

When I run the code, I see:

Array
(
    [a] => v1
    [b] => v2
    [hello] => Array
        (
            [world] => !!!
        )

)

Due to the line in function:

$array = $value;

it should replace $array value, but it does not happen.

My function is based on code snippets are given here: Using a string path to set nested array data Thank you.

Community
  • 1
  • 1

1 Answers1

1

Let's examine this one step at a time.

The parameter $array is a local variable within the function which contains a reference to some external array being passed in.

foreach ($path as $p) {

This iterates over ['hello', 'world']

    $array = &$array[$p];

Take the original array, and "index" it with $p (i.e. [hello]). This does not currently exist so it is added to the original array. Then take a reference to that new member and save it in the local variable $array. I.e. you just created a new member of the original array, and the local variable $array no longer points to the original external array.

On the second iteration, take the variable currently pointed to by $array (see just above) and index it with $p (world). This does not exist, so create it.

}

At this point $array points to the member {original array}[hello][world]. I use the syntax {original array} here because you no longer have a reference to it, only a reference to an array two levels nested within it.

$array = $value;

This sets the value of that member to !!!, giving exactly the data structure you see.

Jim Garrison
  • 85,615
  • 20
  • 155
  • 190
  • Despite on SO asks to avoid "thanks" in the comments, I still thank you here, Sir. Well.. Lookks clear now, but am I correct it is much better to use differently named variables to make code more understandable? – Vsevolod Azovsky May 23 '16 at 03:19