How To Decide when to use a loop

Logan

New Member
I'm writing an informal test on programming basics on Monday (18 May), and I need to know (but can't find anything) how do you decide when to use what type of loop?

How do you decide you need a for..next loop, or a for each..next, or a while...wend loop?

I've always just thought "OK, I need it to do this while the recordset is still open, so a while loop should do"

Any answers or links you can post will be really appreciated.
 

conor

New Member
Well in PHP anyway this is what I do.

Use a while loop when you want to say "while something equals something else do this". Fpr example this while loop keeps executing until this function returns true:

Code:
function getValue(){
    // blah blah blah
    if($blah!=$ahh) return false;
    return true;
}

$val=getValue();

while($val==false){
   echo 'returned false <br/>';
}

or you could use it for a database query. This statement continues until all the rows in the database have been cycled through:

Code:
$query=mysql_query('select * from pages');

while($r=mysql_fetch_array($query)){
   echo 'row: '.$r.'<br/>';
}

You use a for each statement if you want to do something like cycling through an array. For example this code will cycle three times:

Code:
$array=array( 1=>'one',2=>'two',3=>'three' );

foreach($array as $k=>$v){
   echo 'Num: '.$k.' or '.$v.'<br/>';
}

And finally you use a for statement when you want to repeat something a specific number of times. This example will repeat 10 times:

Code:
$num=10;

for($i=0;$i<=$num;$i++;){
   echo $num.'<br/>';
}
 
Top