September 22, 200817 yr This is kind of an academic question - This loop will return each row from a MySQL query: while ($row = (mysqli_fetch_array($r))) { echo $row['value']; } (and this one also returns the same result) for ($i=0; $i<=$num; $i++) { $row = (mysqli_fetch_array($r)); echo $row['value']; } Could someone explain to me how the loop is moving through the query results, since the operation within the parentheses has no apparent incrementation - so I would expect the query to return the initial result (i.e: row 1 of the query) on each pass of the loop calling it. I know that in fact it returns each sequential row from the query each time the loop is executed, I'm just curious as to how it's doing it. I guess it's one of those 'driving' questions, in that I know how to drive, but I don't know how the engine works.
September 22, 200817 yr If you look at the two sections of code, both use the same function: mysqli_fetch_array($r) Neither actually pass any incrementation information to mysqli_fetch_array($r) In the second snippet, where you are manually controlling the number of iterations, you are not telling the function what iteration you are on, you are simply calling the function over and over again, the same as the first. Calling mysqli_fetch_array($r) automatically fetches the next unread record from the result set. Thus, no matter what you use to create the loop (while or for) you are doing the same thing. The while loop tests to see if mysqli_fetch_array($r) still returns a new array and exits when it doesn't. The for loop requires you to know how many result sets you have and to do the math correctly. Thus I'd say the while loop is safer.
September 22, 200817 yr Interesting question ... I played with it for a while (pun intended) and my conclusion is that php is using a shortcut to create something like this: $ar = array("a" => 1,"b" => 2, "c" => 3); while (list($key, $value) = each($ar)) { echo "Key: $key; Value: $value<br />\n"; }
September 22, 200817 yr Author Thanks for the quick response folks. I like to know how the genie's getting in and out of the bottle, it's not enough to get my 3 wishes!!
Create an account or sign in to comment