views:

100

answers:

5

Hi, I have been working with C# so this is quite strange for me:

    while($variable=mysql_fetch_assoc)

{   $X=$variable['A'];
    $Y=$variable['B'];  
}

If it is like an ordinary loop, then X,Y will be reset with every loop, right?

I have not been able to look up in PHP manual how it works. I guess that in each loop it advances to next element of assoc.array. But what is this generally called in PHP? I am just not used to see '=' in loop condition.

+1  A: 

It means something like "until you can mysql_fetch_assoc() an element from the variable you pass to that function, then do the body of the while.

It returns an array if it can find an element, FALSE otherwise, so you can exit the loop.

LucaB
+3  A: 

Assignment in PHP is an expression that returns the value that was assigned. If a row was retrieved then the result will be non-false, which will allow the loop to continue.

Ignacio Vazquez-Abrams
+3  A: 

mysql_fetch_assoc() (and its related functions) advance $result's internal pointer every time it gets called. So $variable will be assigned a new row array every time the while condition is checked. After the last row is returned, mysql_fetch_assoc() can't advance the internal pointer anymore, so the next attempt to call it will return false. Once $variable becomes false, the condition is no longer satisfied and the loop exits.

In PHP (also JavaScript et al), a condition is true as long as it doesn't evaluate to either zero, an empty string, NULL or false. It doesn't have to evaluate to a boolean value. That's why such a loop works.

EDIT:

If it is like an ordinary loop, then X,Y will be reset with every loop, right?

Yes, they'll be reassigned with the new values from each new row that is fetched.

BoltClock
Also the solution is just to declare them out of the while loop?
Petr
Depends on what you need them for. I can't tell much from your code.
BoltClock
+2  A: 

Perhaps looking at the code like this would be useful:

while (($variable = mysql_fetch_assoc($result)) == true) {
  // loops until the fetch function returns false (no more rows)
  // $variable will have be an associative array containing the 'next' row from the recordset in $result
}

It's a shorthand way of doing this:

$variable = mysql_fetch_assoc();
while ($variable) {
  // loop

  $variable = mysql_fetch_assoc();
}
HorusKol
A: 

It's just short form of this code:

$variable = mysql_fetch_assoc($res);
while($variable != FALSE) {
  // do something
  $variable = mysql_fetch_assoc($res);
}
Col. Shrapnel