note 74596 deleted from function.array-keys by bjori
| From: | bjori@php.net | Date: | Fri, 20 Apr 2007 09:14:56 +0000 |
| Subject: | note 74596 deleted from function.array-keys by bjori | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-125592@lists.php.net to get a copy of this message | ||
Note Submitter: Spudley
Reason: bad code
----
If you use foreach() to loop through an array, each iteration of the loop will generate a new copy
of the array element in the 'as' variable:
For example if you do:
<?php
foreach($myarray as $myelement) {
print_r($myelement);
}
?>
each time it loops, a new copy of the current array element will be created in $myelement.
There's two problems here: Firstly, if you change data in $myelement, it won't affect the
original copy in $myarray. The second problem is that if your array contains large elements, it is
inefficient use of memory to make copies; it would be better to reference the original.
The solution to both these problems is array_keys().
The example would now look like this:
<?php
foreach(array_keys($myarray) as $mykey) {
print_r($myarray[$mykey]);
}
?>
This is particularly useful if you have an array of objects to loop through, as creating new
instances of the objects may have additional unexpected effects.
I hope this is of some help.