php: foreach


Just an FYI to anyone building Object Oriented applications with PHP, the foreach construct which allows you to loop through the elements in an array does so on a copy of the array.

Therefore if you run through an array of objects with a foreach loop any changes to those objects aren’t maintained outside that current iteration.

In PHP 5 there is a quick solution to preceed the value in the foreach with an ampersand (&). Otherwise the best way to loop through the array is with a good old fashion for loop – easy for numerical arrays, but with an associative array you will probably need to play with array_keys.

This may not affect anyone else but I just encountered that problem myself – something I knew about, but it can certainly snag things up if not considered. :)

Written by Colin Bate