...

View Full Version : for loop vs while



Coastal Web
05-24-2005, 03:18 AM
Hola folks, quick question regarding proper coding technique.
I just wanted to know if for loops process any faster than while loops?

Or is it okay to use while loops 99.9% of the time, such as l myself do?

I was just wondering if there were any ramifications for practicing this.

Samantha G.

SeeIT Solutions
05-24-2005, 03:32 AM
for loops require setting another variable where as while loops often dont, this means they should be less straining on resources.

Also while loops go until they aren't need any more and for loops you have to set how long they go for which means you may have to use a function such as count() or mysql_num_rows() to see how many times you want it to repeat which can also take processing time.

Coastal Web
05-24-2005, 03:39 AM
Well, l guess the main use l make of while loops is something like:


$i=0;
while($i<$someNumber){
//do something...

$i++;
}

So l'm using the while loops for 'generic' for loops, l just wanted to know if that's bad practice.

Samantha G.

CrAzY_J
05-24-2005, 03:52 AM
for() for me :)

I just like them better, better to go around with and so

SeeIT Solutions
05-24-2005, 04:29 AM
well a for loop is designed for that purpose so I guess it could be classed as bad practice.

Using a for loop for the same example you showed cuts out 2 lines because you set the variable and increment it all in the 1 line. you could try using a microtime function to test exactly how much time the 2 methods take to do the same function.

Spookster
05-24-2005, 05:14 AM
A for loop is a count controlled loop where as a while loop is a sentinel controlled loop. Although you could make a while loop act as a count controlled loop, that is not what it was designed for.

marek_mar
05-24-2005, 06:22 AM
There is almost no difference between those two:


<?php
while(condition)
{
// do something.
$i++;
}
// Is the same as
for( ; condition; )
{
// Do something.
$i++;
}
// You could do something like this:
while()
{
// do something
if($condition)
{
break;
}
$i++;
}

for( ; ; )
{
// do something
if($condition)
{
break;
}
$i++;
}
?>

For loops you keep the varables you need only inside the loop and expressions
executed after each loop execution


for($i = 0, $j = 10, $n = count($someArray); $i < $n; $i++, $j--)
{
print '$i = ' . $i . "\n" . '$j = ' . $j . "\n";
}

You could do all that with a while loop too


$i = 0;
$j = 10;
$n = count($someArray);
while($i < $n)
{
print '$i = ' . $i . "\n" . '$j = ' . $j . "\n";
$i++;
$j--;
}

SeeIT Solutions
05-24-2005, 06:36 AM
Marek, your post is just repeating the other posts, and the code you gave in the first section was definately bad practice.

She knows that both CAN be used she wanted to know IF it was bad practice to use a while loop instead of a for loop, which the answer is technically YES. For loops are designed for the purpose she has pointed out even tho while loops can do the same thing.

Ultragames
05-24-2005, 06:44 AM
While loops and for loops really have different uses. If your going to set a counting variable, (such as printing the first 10 of something) then it makes sence to use a for loop.
for( $i=0; $i<10; $i++ ){
echo "blah";
} This can of course be done with a while loop, but it requires 2 more lines, (assuming you seperate your code as I do.)
$i = 0;
while( $i < 10 ){
echo "blah";
$i++;
}

However, sometimes while loops are better than for loops. When dealing with MySQL results, with a for loop you would have to get the mysql_num_rows variable, however with a while loop, you do not:
while( $row = mysql_fetch_array($result) ){
echo "blah";
}
vs

$num = mysql_fetch_array( $result );
for( $x=0; $x<$num; $x++ ){
echo "blah";
}


I hope this helps.

marek_mar
05-24-2005, 03:24 PM
You can use the for loop...


for($i=0; $row = mysql_fetch_array( $result ); $i++){
echo $i . ': ' . $row['something'];
}

SeeIT Solutions
05-24-2005, 03:26 PM
The point is though, it is bad practice.

marek_mar
05-24-2005, 03:28 PM
Why would that be?

SeeIT Solutions
05-24-2005, 03:33 PM
Refer to Ultragames post ^^

Anyway, I think this thread is over, Samantha has her answer...I hope

AaronW
05-24-2005, 03:34 PM
In this day and age with processors becoming more and more powerful, performance is becoming less and less of a priority. While you should still take care not to overload the processor with redundant calls, you should be more concerned with the legibility of your source.


$i = 0;
while (++$i < 100)
{
}

Is it faster? It doesn't matter. It looks far more confusing than the structure it's emulating:


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

I'm not sure what your motivation for seeking an alternative is, but if it's to make your code run more quickly don't bother. Any gain in speed is going to be negligible unless you get into the hundreds-of-thousands of iterations.

marek_mar
05-24-2005, 03:47 PM
It doesn't make sense SeeIT. Both loops are are almost identical and there is no real performance gain. Why would be using a for loop a bad practice?

AaronW
05-24-2005, 03:54 PM
By the way, the for loop's first and last expressions can be comma-seperated:



for ($i = 0, $j = 0; $i < 100; echo $i.' vs. '.$j, $i++, $j = 100 - $i);


Some may find it harder to read though. It can definitely get confusing if you abuse it and throw your entire block inside the last expression :eek:

SeeIT Solutions
05-24-2005, 03:58 PM
while
while loops are the simplest type of loop in PHP.


for
for loops are the most complex loops in PHP.

Argue with them if you want...

AaronW
05-24-2005, 04:00 PM
Being the most complex looping structure doesn't make them complex, just relatively complex. They're both easy, and they both have their own uses. You can emulate a while () with a for () using for (;$row = mysql_fetch_array ($result);) but it'd be stupid. Why is the opposite any different?

delinear
05-24-2005, 04:12 PM
However, sometimes while loops are better than for loops. When dealing with MySQL results, with a for loop you would have to get the mysql_num_rows variable, however with a while loop, you do not:
while( $row = mysql_fetch_array($result) ){
echo "blah";
}
vs

$num = mysql_fetch_array( $result );
for( $x=0; $x<$num; $x++ ){
echo "blah";
}

I know I'm just being pedantic here but you can emulate a while loop with a for loop and get the same effect without having to send a mysql_num_rows query:


for ($i = 1; ; $i++) {
if(!$tmp=mysql_fetch_assoc($result)) {
break;
} else {
$row[] = $tmp;
}
}

I know, I know... and I'm meant to be working too :rolleyes:

delinear
05-24-2005, 04:15 PM
I'm with Aaron, there are loads of ways to do these things but at the end of the day, unless you're going to actually see some improvements you are better to stick with whatever method you find easiest to read. That one millionth of a second speed gain might seem like a good idea now, but when you come to change your code in six months and realise you can't make sense of what you wrote or why you will certainly not think it was such an achievement.

marek_mar
05-24-2005, 04:42 PM
We won't agree here fast... there are not many places where you don't need to increment a number. All examples showing how to get rows from a DB use the while loop becouse they don't need the other two "arguments" the for loop has. But if you need to index the results many just expand on the while loop when they could use a for loop. You can avoid all arguments in both loops and put the condition in an if statement. This means that it doesn't really matter what you use as the difference is only coding style.

AaronW
05-24-2005, 04:44 PM
But coding style matters, so it does matter which loop you choose. There are consequences. You'll develop bad habbits and illegible source which will cost you and/or others development time in the future while you or they try to decipher whatever it is you've written.

marek_mar
05-24-2005, 04:56 PM
I'm happy with my coding style (How self-centerd I am...). You're the first one who thinks it's bad. It would be best to know all possibilitys not just to read others code but most of them are usefull on some (rare) occasions.

Spookster
05-24-2005, 05:40 PM
As I stated earlier each type of loop was designed with a specific purpose in mind. It's a matter of personal preference which type of loop you use for the task at hand. It can be considered bad programming style if you need to perform a count controlled task and you use a sentinel controlled loop. It would make more sense to use a count controlled loop for a count controlled task. If your task involves looping until a certain condition is met then it would make the most sense to use a sentinel controlled loop.

Coastal Web
05-25-2005, 12:20 AM
Wow lots of good examples on both sides of the argument here and l thank you all for posting your opinions on the matter.

For me, l will continue to use the while loops where a forloop would probably look "neater" or "cleaner" ... (it's just force of habit l guess). You know what it's like when you get into the "coding zone" and your fingers do all thinking, and the work.... coding auto-pilot so to speak.

In any event, thanks for the help folks.

Samantha Gram.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum