Let me prefix this by saying that I know what foreach
is, does and how to use it. This question concerns how it works under the bonnet, and I don\'t want any an
PHP foreach loop can be used with Indexed arrays
, Associative arrays
and Object public variables
.
In foreach loop, the first thing php does is that it creates a copy of the array which is to be iterated over. PHP then iterates over this new copy
of the array rather than the original one. This is demonstrated in the below example:
', print_r($numbers, true), '
', '', print_r($numbers, true), ''; # shows the original values (also includes the newly added values).
Besides this, php does allow to use iterated values as a reference to the original array value
as well. This is demonstrated below:
', print_r($numbers, true), '
';
foreach($numbers as $index => &$number){
++$number; # we are incrementing the original value
echo 'Inside of the array = ', $index, ': ', $number, '', print_r($numbers, true), ''; # we are again showing the original value
Note: It does not allow original array indexes
to be used as references
.
Source: http://dwellupper.io/post/47/understanding-php-foreach-loop-with-examples