I am a dead beginner with PHP and have been reading through ‘PHP for the Web: Visual Quickstart Guide 4th Ed.’ by Larry Ullman and have a question regarding something I came across in the book.
At the end of each chapter he has a few questions for review and I am stuck on one of them and not sure if I have the correct answer or the correct train of though regarding it.
The question is as follows:
Without knowing anything about $var will the following conditional be TRUE or FALSE? Why?
if ($var = 'donut') {...
I am apt to say that it will be false because we don’t know if $var has been assigned the value donut yet within the program but I am not sure.
Can anyone help explain this to me so I can grasp this concept and feel confident about it?
This conditional will always evaluate to
TRUEbecause the valuedonutis assigned, and then the value of$varis returned to theif()statement. The assignment happens first.A successful assignment to a variable causes that variable to be returned immediately. A non-empty string is a "truthy" value, and is returned as such.
If instead it was assigned as:
It would evaluate to
FALSE, according to PHP’s boolean evaluation rules:Addendum
Just to add, as a practical example of assignment inside a flow control conditional you probably see almost every day — the
while()loop we typically use to retrieve a rowset from a MySQL result resource: