note 92300 deleted from function.current by danbrown

From: Date: Sat, 18 Jul 2009 00:31:30 +0000
Subject: note 92300 deleted from function.current by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-158447@lists.php.net to get a copy of this message
Note Submitter: ratfactor at gmail dot com ---- 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

« previous php.notes (#158447) next »