note 92300 added to function.current

From: Date: Sat, 18 Jul 2009 00:05:04 +0000
Subject: note 92300 added to function.current
Groups: php.notes 
Request: Send a blank email to php-notes+get-158444@lists.php.net to get a copy of this message
While not common, one occasionally needs a look-ahead or look-behind ability while looping through the elements of an array. It can be done with prev(), next(), and current(). The following example is NOT the most compact possible version, but it is the least error-prone and most flexible: <?php $nums = array(1,2,3,4,5); for(reset($nums), $i=0; $n=current($nums); next($nums), $i++){ // look behind $behind=' '; if($i>0){ $n=prev($nums); $behind=$n; $n=next($nums); } // look ahead $ahead=' '; if(next($nums)){ $n=current($nums); $ahead=$n; $n=prev($nums); } echo "$i: $behind $n $ahead\n"; } ?> Results: 0: 1 2 1: 1 2 3 2: 2 3 4 3: 3 4 5 4: 4 5 ---- Server IP: 64.71.164.2 Probable Submitter: 24.251.157.169 ---- Manual Page -- http://www.php.net/manual/en/function.current.php Edit -- https://master.php.net/note/edit/92300 Del: integrated -- https://master.php.net/note/delete/92300/integrated Del: useless -- https://master.php.net/note/delete/92300/useless Del: bad code -- https://master.php.net/note/delete/92300/bad+code Del: spam -- https://master.php.net/note/delete/92300/spam Del: non-english -- https://master.php.net/note/delete/92300/non-english Del: in docs -- https://master.php.net/note/delete/92300/in+docs Del: other reasons-- https://master.php.net/note/delete/92300 Reject -- https://master.php.net/note/reject/92300 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#158444) next »