Avatar ·

How foreach actually works in PHP? Detailed analysis with examples

Hello everyone! I've been writing PHP for a few months now, but I still don't fully understand how foreach works. The documentation says it's a "convenient way to iterate over arrays," but I'm troubled by questions I can't find answers to.\n\nFor example, I know that when using foreach with a reference (&$value), you can modify array elements. But why does the $value variable still reference the last element after the loop? This leads to unexpected bugs.\n\nI'm also interested in: what happens "under the hood"? Is a copy of the array created with each foreach? I've heard that PHP uses a copy-on-write mechanism, but I don't understand how this works in the context of loops.\n\nHere's an example that confuses me:\n\n```php\n$array = [1, 2, 3];\nforeach ($array as &$value) {\n $value *= 2;\n}\n// Now $array =