PDA

View Full Version : Loops


Niko
04-07-2008, 05:50 PM
What to use when...

What's the difference between For Loop, While Loop and For Each Loop ?

thanks

cu-it-up
04-08-2008, 03:12 PM
The purpose of a loop is to do something over and over again until the task has been completed.

The while loop is used to do a task over and over as long as the specified conditional statement is true.
(eg)
while ( conditional statement is true){
//do something code;
}

The for loop is basically a while loop but with a little more code added to it.
(eg)
for ( initialize a counter; a conditional statement; finally increment the counter){
do this code;
}

(eg)
for ( $counter = 20; $counter <= 200; $counter += 20) {

The while and for loop will continue until some condition fails.
However the For Each loop will iterate until it has gone through every item in an array.

(eg)
foreach( $spouse_age as $name => $age){
echo "Name: $name, Age: $age <br />";
}

Hope this helps