note 115207 added to control-structures.foreach

From: Date: Thu, 12 Jun 2014 13:12:18 +0000
Subject: note 115207 added to control-structures.foreach
Groups: php.notes 
Request: Send a blank email to php-notes+get-199670@lists.php.net to get a copy of this message
This is a decent, simple, and easy way to reference other values of an associative array when using foreach. (effective "next", "prev", etc.) The only care that needs to be taken is if the array is HUGE in size, so you don't run into memory use problems. (and potential speed issues) This example uses the 'primary' array, $aPublishSeq, which is ksort-ed to put the array in order according to the associative keys. The array is then copied using a foreach loop to make a duplicate array where the key and value order correspond to the first array, but the keys are sequential numeric starting at zero. ksort ($aPublishSeq, SORT_STRING); // put them all in the right order keeping array keys foreach ($aPublishSeq as $aValue) $aPublishIdx[] = $aValue; // duplicate array using corresponding sequential numeric keys Now, in the usage foreach loop, an index variable is used to keep in sync with the associative array. $PubIdx = -1; // start at -1 to start at 0 below foreach ($aPublishSeq as $sKey => $sValue) { ++$PubIdx; // index into $aPublishIdx array of corresponding element in $aPublishSeq array (for "next" element check, etc.) echo $aPublishIdx[$PubIdx - 1] // previous array value echo $aPublishIdx[$PubIdx] // current array value echo $aPublishIdx[$PubIdx + 1] // next array value .... It's simple, but it works, and without much muss or fuss. ---- Server IP: 72.52.91.14 Probable Submitter: 72.52.91.14 ---- Manual Page -- http://php.net/manual/en/control-structures.foreach.php Edit -- https://master.php.net/note/edit/115207 Del: integrated -- https://master.php.net/note/delete/115207/integrated Del: useless -- https://master.php.net/note/delete/115207/useless Del: bad code -- https://master.php.net/note/delete/115207/bad+code Del: spam -- https://master.php.net/note/delete/115207/spam Del: non-english -- https://master.php.net/note/delete/115207/non-english Del: in docs -- https://master.php.net/note/delete/115207/in+docs Del: other reasons-- https://master.php.net/note/delete/115207 Reject -- https://master.php.net/note/reject/115207 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#199670) next »