note 74596 added to function.array-keys

From: Date: Thu, 19 Apr 2007 10:11:44 +0000
Subject: note 74596 added to function.array-keys
Groups: php.notes 
Request: Send a blank email to php-notes+get-125565@lists.php.net to get a copy of this message
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. ---- Server IP: 194.145.210.4 Probable Submitter: 212.84.170.86 (proxied: 1.1 SKYMARKETISA) ---- Manual Page -- http://www.php.net/manual/en/function.array-keys.php Edit -- https://master.php.net/note/edit/74596 Del: integrated -- https://master.php.net/note/delete/74596/integrated Del: useless -- https://master.php.net/note/delete/74596/useless Del: bad code -- https://master.php.net/note/delete/74596/bad+code Del: spam -- https://master.php.net/note/delete/74596/spam Del: non-english -- https://master.php.net/note/delete/74596/non-english Del: in docs -- https://master.php.net/note/delete/74596/in+docs Del: other reasons-- https://master.php.net/note/delete/74596 Reject -- https://master.php.net/note/reject/74596 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#125565) next »