Web Design Forum  
 
Go Back   Web Design Forum > Web Software > Programming

Reply
 
LinkBack Thread Tools Display Modes
Old 05-14-2009, 09:28 AM   #1
Bronze Member
 
Join Date: Apr 2009
Posts: 25
Default How To Decide when to use a loop

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.
Logan is offline   Reply With Quote


Old 05-14-2009, 01:10 PM   #2
Gold Member
 
conor's Avatar
 
Join Date: Oct 2008
Location: Ireland
Posts: 349
Default

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/>';
}
__________________
Conor
conor is offline   Reply With Quote
Reply

Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On



All times are GMT. The time now is 04:57 AM.


Camera Forum - Computer Forum - Web Design Forum

Powered by vBulletin® Version 3.8.7
Copyright ©2000 - 2012, vBulletin Solutions, Inc.
Content Relevant URLs by vBSEO 3.6.0 ©2011, Crawlability, Inc.