Page 1 of 1

Properties of a while loop

Posted: Tue Apr 04, 2006 7:06 pm
by Benjamin
I had a little bug in some code I wrote, I ended up tracking it down to a while loop. Are while loops supposed to stop executing when a condition is no longer true, even if it hasn't even completed the loop yet?

Here is an example:

Code: Select all

while (isset($Record[$RecordNumber])) {
    $RecordNumber++;  // line 2
    $TotalRating = $TotalRating + $Record[$RecordNumber]['Rating'];  // line 3
  }
If $Record[1] doesn't exist, this code will stop executing and break out of the loop at line 2 [ie line 3 will never be executed], and the results won't be correct. If I switch lines 2 and 3, it works fine.

Posted: Tue Apr 04, 2006 7:59 pm
by Nathaniel
Say you have 3 elements in array $Record. If $RecordNumber = 3, your code will update it to 4 and the script will try to add an element that doesn't exist to $TotalRating (i.e., $Record[4] doesn't exist.)

So swap the two lines, and you'll be good.

Posted: Tue Apr 04, 2006 8:08 pm
by John Cartwright
whats wrong with foreach() ?

Posted: Tue Apr 04, 2006 9:53 pm
by andre_c
the condition is only checked at the beginning of each iteration, never in the middle of it
so the code will never stop at line two, if the condition is true it will do both line 2 and 3, and if the condition is false it will break out before it executes either line

Posted: Tue Apr 04, 2006 10:35 pm
by Benjamin
Ok, I thought the while loop was stopping, I forgot that line 3 was dependant on the record number as well. Made me wonder there for a bit.