views:

129

answers:

8

It's a pretty simple question, I always have to go check here and then I hit my head and say it's so obvious. But really after a week of not using it I usually end up writing

for ($i = 1;  $i++; $i <= 10;) {
    echo $i;
} 

some Mnemonic might help

+7  A: 

ICE:

  • Initialisation
  • Check
  • Execute
Wrikken
+1 never heard of that one... very nice.
Fosco
I like this one =)
Moak
and now we need a mnemonic to associate FOR with ICE...
Cawas
I'm always for icecream, aren't you? _I scream **for** **ice** -cream_
Wrikken
A: 

I may be daft but don't you want this structure:

for ( $i = 1;  $i <= 10; $i++ )
{
    echo $i;
} 

I don't know of a Mnemonic to remember this structure I've always just seen it as:

STARTING OFF; DO WHILE THIS; PERFORM AFTER EACH ROTATION

Rather:

DEFINE PRIOR TO EXECUTION; DEFINE EXECUTION LIMITS; DEFINE OPERATION FOR EACH ROTATION

Marco Ceppi
The _wrong_ structure was an example why he needed an mnemonic :)
Wrikken
of course i wanted that structure, my point was that I mix it up ^^
Moak
A: 

Just remember that the guard is always checked before the increment, so you write it before.

If you don't remember the guard is checked before the increment, you're in bigger trouble, because you don't know what the loop will do :p

Artefacto
+2  A: 

They go in order.

for (expr1; expr2; expr3)

expr1: Evaluated once at the beginning of the loop
expr2: Evaluated at the beginning of each iteration of the loop
expr3: Evaluated at the end of each iteration of the loop

You want to initialize first, check the condition second, and increment (or decrement) your counter last.

Bill the Lizard
+1 but how could i relate this to real life? =)
Moak
@Moak: Programming *is* my life. ;)
Bill the Lizard
+2  A: 
     START -> CHECK FOR DANGER -> MOVE AHEAD 

for( $i = 0 ;    $i < 100 ;         $i++    )

Hope it helps :-)
Best of luck!

TheMachineCharmer
+1 I guess I am always in a rush and end up checking after I'm hanging over the cliff
Moak
In that case no one can save you! Gravity will not fail my friend! :)
TheMachineCharmer
+5  A: 

Think logical! The order is the same as the expressions are evaluated.

for ($i = 0; $i < 10; ++$i) {
    echo $i;
}
// is same as
$i = 0; // 1.
while ($i < 10) { //2.
    echo $i;
    ++$i; // 3.
}
nikic
A: 

SAM

  • Start your engine
  • Are we there yet?
  • Move
stillstanding
+2  A: 

F irst (initialisation) O Only while (condition) R Rolling on (incrementing or decrementing)

brumScouse