Avatar ·

How foreach actually works in PHP? Understanding copying and references

Hello everyone! I started learning PHP and encountered very strange behavior of the `foreach` loop. I wrote simple code, but the results confused me. ```php 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 ) // I expected all values to be doubled! ``` I thought that `$value` was a reference to the array element, but it turned out to be a copy. Okay, then I tried using `&`: ```php 2 [1] => 4 [2] => 6 [3] => 8 [4] => 10 ) — works! ``` But then I read that doing this is dangerous because `$value` remains a reference to the last e