简体   繁体   中英

Assign variable value in php

i'm just confused about assigning variable values on php to another one , how does it work?! for Example:

 <?PHP
    $var1=mysqli_fetch_array($query);
    while($var2=$var1)
     {
       echo $var2[$key];   /** this wont't work Correctly however $var1 it's 
       value = to mysqli_fetch_array**/
     }

    while($var1=mysqli_fetch_array($query))
     {
      echo $var1[$key];   /** this will work , why ! **/
     }

 ?>

A peculiarity in PHP's assignment behaviour, is that it also returns the result of the assigned value. This allows for statements such as:

$a = $b = $c = 3; // All of a, b and c will equal 3

And:

while ($variable = call_a_function()) {
  do_something_with($variable);
}

In the latter example, variable gets assigned to the output of call_a_function() at the beginning of the loop iteration; as soon as call_a_function() returns a value that evaluates to false , the loop ends. If the returned value does not evaluate to false , variable will contain whatever value was returned, until it gets overwritten again.

Your examples use a similar behaviour. The crucial difference between

$var1=mysqli_fetch_array($query);
while($var2=$var1)
{
  echo $var2[$key];
}

And:

while($var1=mysqli_fetch_array($query))
{
  echo $var1[$key];
}

...is that in the first example, $var1 is only assigned to the return value of mysqli_fetch_array($query) before the loop starts, while in the second example, $var1 is assigned to the return value of mysqli_fetch_array($query) in every iteration of the loop .

What makes the two pieces of code crucially different, in the end, is the fact that mysqli_fetch_array($query) returns different results, depending on circumstances.

Combining the code snippets into an example that works as intended, yet uses $var2, yields:

while($var2=$var1=mysqli_fetch_array($query))
{
  echo $var2[$key];
}

or

$var1=mysqli_fetch_array($query); // ask first time
while($var2=$var1)
{
  echo $var2[$key];
  $var1=mysqli_fetch_array($query); // ask again, because the answer changed
}

TL;DR: The first example asks a question once, the second asks a question many times. In this case, the intended behaviour of your code requires the question to be asked multiple times, because the answer changes over time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM