Iterator first item?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • cjl

    Iterator first item?

    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?
    Pseudocode:

    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.

    -CJL

  • frizzle

    #2
    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?

    Comment

    • Chung Leong

      #3
      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
      next($data);
      while(list($ind ex, $item) = each($data)) {
      // do stuff with the rest
      }

      Comment

      Working...