Why are assignment operators (=) invalid in a foreach
loop? I\'m using C#, but I would assume that the argument is the same for other languages that support
Because you can't use a foreach
loop to modify an array you're looping through. The loop iterates through the array, so if you try to modify what it's iterating through then unexpected behavior may occur. Furthermore, as Darin and DMan have pointed out, you're iterating through an IEnumerable
which is itself read-only.
PHP makes a copy of the array in its foreach
loop and iterates through that copy, unless you use references, in which case you'll modify the array itself.