NYCPHP Meetup

NYPHP.org

[nycphp-talk] Loop next/previous offset boundaries in Arrays

Dan Cech dcech at phpwerx.net
Thu Oct 6 09:22:04 EDT 2005


Cliff,

I'm not sure exactly what you're trying to do, but you may find the 
following useful:

$myarray = array();
unset($prev);

foreach ($myarray as $curr) {
   if (isset($prev)) {
     // compare $prev and $curr
   }
   $prev = $curr;
}


$myarray = array();
unset($curr);

foreach ($myarray as $next) {
   if (isset($curr)) {
     // compare $curr and $next
   }
   $curr = $next;
}

These won't work properly if the arrays contain null values, though I'm 
sure someone on the list will have an idea on that one.

Dan

Cliff Hirsch wrote:
> In a loop, a common function seems to be comparing a current array value
> with the next or prior array value. Seems easy, except for the first and
> last loops, which generate undefined offset errors. Is there a "clean"
> way to get around this other than testing for the first or last loop
> value, which generates a lot of extra code.
>  
> Cliff Hirsch
> 
> 
> 
> ------------------------------------------------------------------------
> 
> _______________________________________________
> New York PHP Talk Mailing List
> AMP Technology
> Supporting Apache, MySQL and PHP
> http://lists.nyphp.org/mailman/listinfo/talk
> http://www.nyphp.org




More information about the talk mailing list