while loop in php with assignment operator

前端 未结 7 692
闹比i
闹比i 2020-12-17 10:41

the code I\'m looking at does this...

while ($info=mysql_fetch_array($data_jurisdiction))
{
//some stuff
}

I\'m wondering what does this wh

相关标签:
7条回答
  • 2020-12-17 11:05

    great answer from hakre. what is said is that

    while ($info=mysql_fetch_array($data_jurisdiction))
    

    will execute in the same way as this

    while (mysql_fetch_array($data_jurisdiction)==true)
    

    or even this

    $info = mysql_fetch_array($data_jurisdiction);
    if($info==true)
    

    so keep in mind that if mysql_fetch_array($data_jurisdiction) returns anything that can be evaluated to false, the assignment won't work. some of those values are (and I know I will forget a few:

    • 0
    • "0"
    • false
    • "false"
    • NULL
    • ""
    • array() (not fully sure about this one)
    0 讨论(0)
  • 2020-12-17 11:10

    as long as $info gets assigned a value other than false, this code will execute?

    Yes.

    0 讨论(0)
  • 2020-12-17 11:14

    For each record $info will be populated with the current row, until it reaches the end of the result set when it will be set to false (which should stop the while loop).

    0 讨论(0)
  • 2020-12-17 11:16

    it does loop and stops if $info is false

    mysql_fetch_array(); clears row by row so there is new result alltimes

    0 讨论(0)
  • 2020-12-17 11:21

    A while loop will execute the nested statement(s) repeatedly, as long as the while expression evaluates to true.

    The expression in your example $info = mysql_fetch_object($data_jurisdiction) checks whether the $info, the assigned value from mysql_fetch_object() is equal to true, after type juggling.

    It is important to understand two things here:

    1. mysql_fetch_object() returns the next row of the result set until the end of the data set is reached, where it returns false. See the method documentation here.
    2. All assigned values of variables which are not equal to 0, or null evaluate to true after type juggling.
    0 讨论(0)
  • From the manual:

    The value of an assignment expression is the value assigned. That is, the value of "$a = 3" is 3.

    Also from the manual about mysql_fetch_array:

    Returns an array of strings that corresponds to the fetched row, or FALSE if there are no more rows.

    Therefore, once there are no more rows, the assignment will turn into:

    $info = false
    

    Which will get evaluated as false in the while condition, causing the loop to terminate.

    0 讨论(0)
提交回复
热议问题