Webeng Webeng - 5 months ago 5
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>";


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


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
, the code inside the while loop would continue to execute. This leads me to infer that the
condition is checking what the resulting value inside
is. So if a boolean is returned into
by the function, then that will be the condition judged by
. That also leads me to believe that if
ends up being a number, then anything
will equate to false, and anything
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.


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.