Properties of a while loop

Not for 'how-to' coding questions but PHP theory instead, this forum is here for those of us who wish to learn about design aspects of programming with PHP.

Moderator: General Moderators

Post Reply
User avatar
Benjamin
Site Administrator
Posts: 6935
Joined: Sun May 19, 2002 10:24 pm

Properties of a while loop

Post 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.
User avatar
Nathaniel
Forum Contributor
Posts: 396
Joined: Wed Aug 31, 2005 5:58 pm
Location: Arkansas, USA

Post 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.
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Post by John Cartwright »

whats wrong with foreach() ?
User avatar
andre_c
Forum Contributor
Posts: 412
Joined: Sun Feb 29, 2004 6:49 pm
Location: Salt Lake City, Utah

Post 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
User avatar
Benjamin
Site Administrator
Posts: 6935
Joined: Sun May 19, 2002 10:24 pm

Post 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.
Post Reply