note 114905 added to function.key

From: Date: Wed, 23 Apr 2014 16:05:16 +0000
Subject: note 114905 added to function.key
Groups: php.notes 
Request: Send a blank email to php-notes+get-199321@lists.php.net to get a copy of this message
Note that using key($array) in a foreach loop may have unexpected results. When requiring the key inside a foreach loop, you should use: foreach($array as $key => $value) I was incorrectly using: <?php foreach($array as $value) { $mykey = key($array); } ?> and experiencing errors (the pointer of the array is already moved to the next item, so instead of getting the key for $value, you will get the key to the next value in the array) CORRECT: <?php foreach($array as $key => $value) { $mykey = $key; } A noob error, but felt it might help someone else out there. ---- Server IP: 72.52.91.14 Probable Submitter: 66.225.132.249 ---- Manual Page -- http://php.net/manual/en/function.key.php Edit -- https://master.php.net/note/edit/114905 Del: integrated -- https://master.php.net/note/delete/114905/integrated Del: useless -- https://master.php.net/note/delete/114905/useless Del: bad code -- https://master.php.net/note/delete/114905/bad+code Del: spam -- https://master.php.net/note/delete/114905/spam Del: non-english -- https://master.php.net/note/delete/114905/non-english Del: in docs -- https://master.php.net/note/delete/114905/in+docs Del: other reasons-- https://master.php.net/note/delete/114905 Reject -- https://master.php.net/note/reject/114905 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#199321) next »