In the project, it is necessary to perform calculations with intermediate saving of each stage into variables. After that, collect all the results into an array with keys of the same name as a variable. Then transfer the array to another function and iterate over it, changing the values ​​only inside the function, without changing the original ones.

// Решил, что в начале работы обнулю все переменные и соберу ссылки на них в массив $var1 = $var2 = $var3 = 0; $busket['var1'] = &$var1; $busket['var2'] = &$var2; $busket['var3'] = &$var3; // далее идут вычисления $var1 = ...; $var2 = ...; $var3 = ...; // передаём массив в другую функцию $niceOutput = string_formatting($busket); // и вот тут переменные $var1 .. $var3 уже изменённые, // чего быть не должно 

But inside the function I already need to work with a copy of the array, in which the values ​​are not linked by references to the original variables.

 function string_formatting($busket) { // вот так скопировать не получается, значения всё равно передаются ссылками $copyBusket = $busket; unset($busket); foreach ($copyBusket as $name => &$value) { // меняем $value } } 

I am only interested in educational purposes in order to understand how to unlink variable references, since The problem has already been solved differently.

  • And why do you even use links? Work with variables, not references to them. - Visman
  • @Visman, apparently the links are to declare an array in advance, and further along the program, as the variables change, the array will also change. Just what prevents $copyBusket from $copyBusket in a loop, not through assignment? Or via array_flip(array_flip($busket)); - BOPOH
  • @BOPOH array_flip there is a danger of losing some data. And how else to copy, except for iteration in the loop? - toxxxa

1 answer 1

You can clone an array by creating an ArrayObject object and then calling the getArrayCopy() method.

 $obj = new ArrayObject($busket); $copyBusket = $obj->getArrayCopy(); 

In this case, $copyBusket and $arr no longer be references to the same array.

  • I already forgot why I need it. but thanks, it is :) - toxxxa