2

I have a sample code. Its strange! Even not making any changes in defined array but still my defined array's value got changed.

$myarr = array(1, 2, 3, 4);
foreach ($myarr as &$myvalue) {
    $myvalue = $myvalue * 2;
}
print_r($myarr); // Output - Array ( [0] => 2 [1] => 4 [2] => 6 [3] => 8 )

Can you please explain, How it happen?

3
  • 3
    remove & in &$myvalue Commented Sep 9, 2018 at 10:07
  • 3
    Read about references. Using them in a loop produces unexpected results. This is explained in the documentation: php.net/manual/en/language.references.whatdo.php Commented Sep 9, 2018 at 10:07
  • What do you mean? You are multiplying each value in your array by 2, in the foreach statement: $myvalue = $myvalue * 2; The output is correct. Commented Sep 9, 2018 at 10:08

3 Answers 3

2

You do change the original array because you are using & in your array loop.

This signal for references as @axiac comments.

In order to avoid changes on your original array use the following for loop:

foreach ($myarr as $myvalue)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks David, I could understand that what exactly mean of reference.
0

you are passing address of myarr, where myvalue uses same address of myarr that why its changing

use this

  $myarr = array(1, 2, 3, 4);
    foreach ($myarr as $myvalue) {
        $myvalue = $myvalue * 2;
    }
    print_r($myarr);

Comments

0

have you tried it without the "&" before $myvalue?

Please read here PHP: What does a & in front of a variable name mean?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.