Liglo App
Liglo App

Reputation: 3819

Clone an array passed by reference

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?

Upvotes: 1

Views: 630

Answers (1)

Yury Fedorov
Yury Fedorov

Reputation: 14928

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.

Upvotes: 4

Related Questions