1

There is this function taking the $feedback argument by reference and modifying it:

private function removeEmptyAnswers(&$feedback)
{
    //Do stuff with $feedback
}

I would like to make a copy of $feedback before it gets changed, to log it:

private function removeEmptyAnswers(&$feedback)
{
    $feedbackCopy = $feedback;
    //Do stuff with $feedback
    MyLog::write(['before' => $feedbackCopy, 'after' => $feedback]);
}

This would be peanuts if $feedback were passed by value, but it is passed by reference, meaning that my $feedbackCopy will also get changed.. or not?

Strange enough not to find any solution for this after 30 minutes of googling.

How to make a copy of an array, which is passed by reference?

Liglo App
  • 3,719
  • 4
  • 30
  • 54
  • 1
    `$feedbackCopy` would not be changed when you change `$feedback`. https://3v4l.org/072Pi So you don't have to change anything actually. – Yoshi Dec 15 '16 at 10:42

1 Answers1

4

It is enough to just assign the array to another variable.

$original = [1, 2, 3];
function meh (&$arr) { $copy = $arr; $copy[0] = 'meh'; }
meh($original);
var_dump($original); // unchanged

function meh1(&$arr) { $arr[0] = 'meh'; }
meh1($original);
var_dump($original); // changed

The original array is not changed in that case, as you see. But if you change the argument, it is changed, as expected.

Also, see this question for more information, as suggested by AnthonyB.

Community
  • 1
  • 1
Yury Fedorov
  • 14,508
  • 6
  • 50
  • 66
  • And once again, PHP generates the *least expected result*. Thank you. – Liglo App Dec 15 '16 at 10:44
  • 1
    Indeed as seen [here](http://stackoverflow.com/questions/2840112/php-making-a-copy-of-a-reference-variable) if you copy a reference without reference operation, the reference copy is not a reference. – Anthony Dec 15 '16 at 10:46