Webeng Webeng - 6 months ago 10
PHP Question

While loop with a function inside the boolean condition

I have seen a lot of code online that has a function assigning a value to a variable inside the boolean condition of a while loop:

while ($var = testfunction($param1, $param2))
{
echo "hello world!<br>";
}


QUESTION:

What is the sequence of events happening inside the boolean condition
($var = testfunction($param1, $param2))
? And what value is being judged by the
while
if it is true or not?

MY OWN TESTS:

I have done my own tests. When the function was completely empty, and returned nothing, the code inside the while loop did not execute, however when the function
testfunction()
returned
TRUE
, the code inside the while loop would continue to execute. This leads me to infer that the
while
condition is checking what the resulting value inside
$var
is. So if a boolean is returned into
$var
by the function, then that will be the condition judged by
while
. That also leads me to believe that if
$var
ends up being a number, then anything
==0
will equate to false, and anything
!=0
will equate to true.

These are my deductions, though I have not found any documentation behind them and I could be wrong in my analysis.

Answer

The whole expression is being executed, and its value converted to a boolean.

($var = testfunction($param1, $param2))

First off, testfunction(...) will be called, and afterwards the assignment will take place. According to the manual:

The value of an assignment expression is the value assigned.

so whatever has been returned and assigned to $var will be converted to a boolean and evaluated by the WHILE loop. If if the value assigned is null, [], 0, etc, code block from the while loop will not be executed. Otherwise it will be executed.