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?

dWinder
  • 11,597
  • 3
  • 24
  • 39
sandeep soni
  • 303
  • 1
  • 12
  • 3
    remove & in &$myvalue – Nomad Webcode Sep 09 '18 at 10:07
  • 3
    Read about [references](http://php.net/manual/en/language.references.php). Using them in a loop produces unexpected results. This is explained in the documentation: http://php.net/manual/en/language.references.whatdo.php – axiac Sep 09 '18 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. – Bandreid Sep 09 '18 at 10:08

3 Answers3

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)
dWinder
  • 11,597
  • 3
  • 24
  • 39
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);
Vaibhav Shettar
  • 790
  • 2
  • 9
  • 20
0

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

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