determine if in first itteration in foreach

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
jmut
Forum Regular
Posts: 945
Joined: Tue Jul 05, 2005 3:54 am
Location: Sofia, Bulgaria
Contact:

determine if in first itteration in foreach

Post by jmut »

how could I determine if the first itteration of foreach.

I now how to determine if last...but first? :roll:

Code: Select all

//determine if in last itteration

foreach ($array as $elem) {
 if (!next($array)) {
 //this is last itteration. no more.
 }
}
Of course I can add a variable or something. I would rather not use weird solutions.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

Code: Select all

$first = true;
foreach ($array as $elem)
{
  if ($first)
  {
    // do something
    $first = false;
  }
}
Image
jmut
Forum Regular
Posts: 945
Joined: Tue Jul 05, 2005 3:54 am
Location: Sofia, Bulgaria
Contact:

Post by jmut »

feyd wrote:

Code: Select all

$first = true;
foreach ($array as $elem)
{
  if ($first)
  {
    // do something
    $first = false;
  }
}
Image
gr....ok I thought I don't need variable. But guess this is as perfect as it gets :)
10x
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Post by RobertGonzalez »

feyd wrote:

Code: Select all

$first = true;
foreach ($array as $elem)
{
  if ($first)
  {
    // do something
    $first = false;
  }
}
Image
I cannot believe that for three years this logic has evaded me. Damn, where have I been?
Image
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

Everah wrote:Damn, where have I been?
Image
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Post by RobertGonzalez »

Pimps smilies are going to be the end of me, I know it.
Image
User avatar
Luke
The Ninja Space Mod
Posts: 6424
Joined: Fri Aug 05, 2005 1:53 pm
Location: Paradise, CA

Post by Luke »

where the hell are you guys getting those?
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Post by RobertGonzalez »

The little yellow Walmart rejects are residing comfortably in a corner of Modville. Right next to the Oompa Loompas.
Post Reply