views:

68

answers:

5

Wondering what would be a good method to get the first iteration on a foreach loop. I want to do something different on the first iteration.

Is a conditional our best option on these cases?

+2  A: 

You can simply add a counter to the start, like so:

$i = 0;

foreach($arr as $a){
 if($i == 0) {
 //do ze business
 }
 //the rest
 $i++;
}
Russell Dias
+1  A: 
first = true
foreach(...)
    if first
        do stuff
        first = false
dutt
+5  A: 

Yes, if you are not able to go through the object in a different way (a normal for loop), just use a conditional in this case:

$first = true;
foreach ( $obj as $value )
{
    if ( $first )
    {
        // do something
        $first = false;
    }
    else
    {
        // do something
    }

    // do something
}
poke
+1 I like this one better than mine.
Russell Dias
I had a "natural" first element, so I use that on the conditional. ;) But I really appreciate this idea. Thanks a lot.
MEM
A: 

hm

<?php
$i = 0;
foreach($ar as $sth) {
    if($i++ == 0) {
        // do something
    }
    // do something else
}

more elegant.

janoliver
Will this actually work? Will $i be really incremented after evaluation of the statement?
yan.kun
@yan Well, either the *post-increment operator* works [as described](http://php.net/manual/en/language.operators.increment.php), or PHP is terribly broken...
deceze
yes. $i++ is evaluated after the expression, ++$i would be evaluated first.
janoliver
Thanks for the info :)
yan.kun
+1  A: 

Even morer eleganterer:

foreach($array as $index => $value) {
 if ($index == 0) {
      echo $array[$index];
 }
}
Klinky