NYCPHP Meetup

NYPHP.org

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

Hans Zaunere lists at zaunere.com
Mon Oct 10 18:33:10 EDT 2005


Hi Cliff,

Cliff Hirsch wrote on Thursday, October 06, 2005 7:54 AM:
> 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.

When I need to do non-trivial tasks in a loop, I typically use a for loop,
rather than a foreach().  It often has some key advantages.  Granted,
there's an added step for associative arrays, but if I know that an array
needs some complex processing, I always try to use an numericly indexed
array.

Anyway, I do things like this, for example:

$ArrayCount = count($somearray);
for( $i = 0; $i < $ArrayCount; ++$i )
{
  if( $i === 0 )
    echo 'The first element';

  if( $i === ($ArrayCount-1) )
    echo 'The last element'
}

By using the numeric index, it makes determining where you are in the array
fast and straightforward.


---
Hans Zaunere / President / New York PHP
   www.nyphp.org  /  www.nyphp.com





More information about the talk mailing list