0

What is exactly the difference in php between &$Value and $value in a foreach loop ? And how it works? In the example below print_r ($arr) will return the array modified on the first loop and unmodified on the second one.

<?php

$arr = array(1, 2, 3, 4);

foreach ($arr as $key => &$value) {
    $value = $value * 2;
    echo "$key => $value; ";
    print_r ($arr);
    echo '<br>';
}

unset ($value);
unset ($key);

echo '<br>Second loop without "&" on value <br>';

foreach ($arr as $key => $value) {

    $value = $value * 2;
     echo "$key => $value; "  ;
    print_r($arr);
    echo '<br>';
}

?>

I now it's a beginner question because I'm one :)

Radu
  • 995
  • 12
  • 23

1 Answers1

1

Pass the value by-reference instead of by-value. Variables passed by reference (using the reference operator '&') can have their values changed inside of functions.
For example, see the examples here

zx485
  • 28,498
  • 28
  • 50
  • 59
FD3
  • 361
  • 2
  • 10
  • Thank you sir. So, if I understand correctly if I don't pass it by reference, I can "play" with the array inside of the foreach loop but outside its values will remain unchanged. So once the loop is finished, the array will remain the same as before as long as I don use passing by reference. – Radu Mar 15 '17 at 18:52
  • If you do pass by reference, make sure to unset it (as it is in your code) otherwise it will still be referenced outside the loop. http://php.net/manual/en/control-structures.foreach.php – FD3 Mar 15 '17 at 19:06