Iterator first item?

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View

Hey all:

Let's say I have the code:

foreach($data as $row)
   do something with each $row

Is there a way to do something specific to the first item iterated?

foreach($data as $row)
   if first time through iteration do something with $row
   else do something which each remaining $row

Is this possible? I think I could use a regular 'for' loop, using the
length of the $data array as a guide, and then an 'if..else' structure
to see if it is the first time through the 'for' loop, but I was
looking for a more elegant solution.


Re: Iterator first item?

You could start a count, and for each time it loops add one up.
When $count == 1, do something, if else do nothing?

Re: Iterator first item?

Well, there's always the "old" way of going through an array using
reset() and each().

$first = reset($data);
// do stuff with first item
while(list($index, $item) = each($data)) {
  // do stuff with the rest

Site Timeline