Я постараюсь объяснить это, чтобы вы поняли это немного лучше, см. Рабочий код здесь . Я надеюсь, что это поможет вам понять эту $curr = &$curr[$key];
строку. $curr
указывает на пустое $arr
до начала foreach
, в foreach
он сохраняет значение $key
в $arr
по ссылке, на которую указывает $curr
, а затем переназначает ссылку навновь сохраненные $key
в $arr
снова указатель $curr
.
// initialize variables
$val = 'it works !';
$arr = [];
// Get the keys we want to assign
$keys = [ 'key_1', 'key_2', 'key_3', 'key_4' ];
// Get a reference to where we start
echo "create a space where to save the first key \r\n";
$curr = &$arr;
// Loops over keys
$i = 1;
foreach($keys as $key) {
echo "**************** Iteration no $i ******************\r\n";
// echo "save the value \"$key\" to the reference created earlier in the \$curr variable for the empty array above where the kesy are actually being saved \r\n";
// get the reference for this key
echo "Now save the value of \$key to the array reference present in \$curr and then assigne the reference of newly saved array item to \$curr again \r\n";
$curr = &$curr[$key];
print_r($arr);
$i++;
echo "\r\n\r\n";
}
// Assign the value to our last reference
$curr = $val;
// visualize the output, so we know its right
print_r($arr);