tags:

views:

178

answers:

6

I know how to do this... I'll give example code below. But I can't shake the feeling that there's a clever way to accomplish what I want to do without using a variable like $isfirstloop.

$isfirstloop = true;
foreach($arrayname as $value) {
 if ($isfirstloop) {
  dosomethingspecial();
  $isfirstloop = false;
 }
 dosomething();
}

Is there any way to execute dosomethingspecial() only on the first loop, while executing dosomething() on every loop, without introducing a variable like $isfirstloop?

Thanks!

A: 
$count = count( $arr );

for ( $i = 0; $i < $count; $i++ ) {
    if ( $i == 0 ) { dosomethingspecial(); }
    doSomething();
}
meder
Great for associated arrays or arrays with non-contiguous numbering.
Michael Krelin - hacker
+4  A: 
foreach ($arr as $i => $val)
{
  if ($i == 0) { doSomethingSpecial(); } // Only happens once.
  doSomething(); // Happens every time.
}
James Skidmore
+1 Exactly how i'd apprach it, of course if it's an associative array this wouldnt work, as you'd get the key instead of the index.
Neil Aitken
You'd have to assume the array is numbered with the first key being zero. Consider an array with unset 0 element.
Michael Krelin - hacker
Exactly what I was looking for. It seems so simple, yet I've never come up with it. Thanks so much!
stalepretzel
+7  A: 

Forgive me if I'm missing something, but why not just do the thing you want before the loop?

dosomethingspecial();
foreach($arrayname as $value) {
 dosomething();
}
Gareth
And if you need the first element for doSomethingSpecial() you can use e.g. reset($arrayname) (if the array may be reset before the loop)
VolkerK
dosomethingspecial() will always be invoked, no matter whether the $arrayname array is populated with elements or not, I would assume he at least wants this to be invoked if its populated at least with one element.
meder
Yes, if you take VolkerK's comment into account.
Michael Krelin - hacker
+1  A: 

Hmm... You can reset the array and then see if you're on the first key:

reset($a); foreach($a as $k => $v) {
    if(key($a)==$k) doIt();
}
Michael Krelin - hacker
A: 
$elem = reset($arrayname);
dosomethingspecial();
while( ($elem = next($arrayname)) !== FALSE ) {
  dosomething();
}
Zed
A: 

Your not gaining any performance from the alternative methods. Your method is just fine.

Cody N