views:

256

answers:

5

I'm reading an ebook on PHP right now, and the author noted that the difference between a while loop and a for loop is that the for loop will count how many times it runs.

So take this:

<?php
    for ($i = 1; $i < 10; $i = $i + 1) {
        print "Number $i\n";
    }
?> 

But wouldn't this be the same as

<?php
    $i = 1;
        while ($i < 10) {
            $i = $i + 1;
            print "Number $i\n";
        }
?>

Or is there some other differences that he didn't point out? (Aside from using while loop for when you're unsure of how long the condition will remain true, such as selecting rows from a database)

I mean, if that's the only difference, can't I just not use the for loop and use the while loop instead?

+3  A: 

Can you? Yes, certainly. But whether or not you should is an entirely different question.

The for loop is more readable in this scenario, and is definitely the convention you'll find used within virtually every language that has looping directives. If you use the while loop, people are going to wonder why you didn't use a for loop.

Adam Robinson
So mostly it's a matter of preference? And standardization?
Rob
Which loop is preferred is a matter of what suits the code, not your personal preference. If you understand how both loops work, you'll come to understand where/when to use each type with experience.
Dolph
While loops are generally more prone to errors, so in general, in my code, I only do them when its a multiline initialization or something tricky that doesn't fit in a for loops declaration
DevelopingChris
I see. Alright thanks guys
Rob
And also wonder why you didn't use $i++
webbiedave
I don't know what $i++ does.
Rob
@Rob: The `++` operator is the increment operator. `$i++` is semantically equivalent to `$i = $i + 1`.
Adam Robinson
Oh thanks Adam. That's nifty. Will $i++ ALWAYS be $i = $i + 1?
Rob
@Rob: Yes, though you can write it both as `$i++` and `++$i`. If it's a statement by itself, there's no behavioral difference. The only difference is if it's part of an expression, like `$j = $i++` and `$j = ++$i`. Putting the `++` at the end makes the increment happen *after* referencing the variable, so `$j` would have the value of `$i` *before* the increment. In the latter example (with `++` before the `$i`), `$j` will be given the value *after* the increment. In other words, after either statement is over, the first statement makes `$j` equal `$i-1` and the second makes `$j` equal to `$i`.
Adam Robinson
Now you lost me. If $j = $i++ ($i + 1) wouldn't the first statement make $j = $i, and the second statement make it equal $i + 1?
Rob
@Rob: I mean comparing the values *after the satements are done executing*. Remember that `$i` is being incremented by 1 in each statement.
Adam Robinson
Oh okay, I see what you're saying now. Thanks, this was really helpful.
Rob
@Rob: It's also worth noting that it appears that `++$i` is (slightly) faster than `$i++` (this is a PHP-only scenario)
Adam Robinson
By slightly faster, do you mean like the difference in speed between echo and print, or an actual real world necessity?
Rob
@Rob: Not a necessity, but given that it's just as easy to type `++$i` as it is to type `$i++`, why not? :)
Adam Robinson
Good point, lol. Thanks (:
Rob
A: 

It's a matter of taste, personal preference and readability. Sometimes a while loop works better logically. Sometimes, a for.

For my personal rule, if I don't need a variable initializer, then I use a while.

But a foreach loop is useful in its own way.

Plus, in the case of PHP's scoping, where all variables not inside of functions are global, it the variable will continue living after the loop no matter which loop control you use.

amphetamachine
So with a for loop, the variable will reset after the loop is complete? Or did I misunderstand that?
Rob
In many other languages *i* would not exist outside a for-loop, and trying to access it outside the loop would cause an error. In PHP however, *i* will be available in the function scope after it has been declared, no matter where.
Internet Friend
Pretend your loop variable doesn't exist outside of your for-loop. If you want to use $i again, be sure to assign it a new value before using it again (re-initialize it). Otherwise, you're teaching yourself a bad habbit that won't work at all in stricter languages (e.g. C or Java) as Internet Friend suggests above. This is the concept of "variable scope."
Dolph
@Rob - Not in PHP, but since how a particular hard-scoped language (like C or Java) interprets the variable initializer is pretty much up to the language, `for (int x = 5;;)` may or may not initialize `x` to within the `for` block. If you need the variable outside of the loop, it's safer to say `int x; for (x=5;;)` to make sure the variable is declared in a parent scope.
amphetamachine
+1  A: 

Functionally, a for loop is equivalent to a while loop; that is, each can be rewritten as the other with no change to the outcome or side effects. However, each has different connotations. A while loop runs while a condition holds; the condition is static, though circumstances change. A for loop runs over a sequence. The difference is important to programmers but not programs, just as choice of variables names are important to programmers even though they can be changed to produce functionally equivalent code. One loop construct will make more sense than the other, depending on the situation.

outis
+3  A: 

A for-loop

for (INIT; CONDITIONS; UPDATE) {
    BODY
}

is basically the same as a while-loop structured like this:

INIT
while (CONDITIONS) {
    BODY
    UPDATE
}

While you could technically use one or the other, there are situations where while works better than for and vice-versa.

gix
Er, what is INIT?
Rob
Loop variable initialization. $i = 1; in your examples.
Dolph
Thank you Dolph
Rob
+2  A: 

Functionally, your two examples are the same. The for for loop is preferable because:

  1. It's more concise and puts all the information about the loop in one place
  2. It makes $i a local variable for the loop
  3. It's the more common way of iterating a set number of times, and therefore makes more intuitive sense to other programmers

Semantics

The third point is really what most people are reacting to, I think.

Conceptually, while means 'I don't know how long this condition will last, but as long as it does, do this thing.'

On the other hand, for means 'I have a specific number of repetitions for you to execute.'

So it's mostly a matter of semantics. Just like in HTML, you can use a <span> like a <p> if you style it like one, but it makes less sense.

Don't forget foreach

Personally, the loop I use most often in PHP is foreach. If you find yourself doing things like this:

for ($i=0; $i < count($some_array); $i++){
  echo $some_array[$i];
}

...then try this:

foreach ($some_array as $item){
   echo $item;
}

Faster to type, easier to read.

Nathan Long