evaluation of assignment in php

user151841 picture user151841 · May 9, 2011 · Viewed 7.3k times · Source

I have a kind of 'basics' question about php. In the example code for fgets, it has this snippet as an example of reading through a file's contents:

while (($buffer = fgets($handle, 4096)) !== false) {
    echo $buffer;
}

How is it that the statement ($buffer = fgets($handle, 4096)) can have a value? Is it a kind of assignment+evaluation of $buffer? I mean, how does it get its value? Is there a name for this? I notice its using strict comparison, so do all assignments evaluate to a boolean true or false?

If I wanted to write a function that could be treated this way, do I have to do anything special, other than return false on certain conditions?

Answer

NikiC picture NikiC · May 9, 2011

In PHP an assignment is an expression, i.e. it returns a value. $buffer = fgets($handle, 4096) will first assign the value to $buffer and then return the assigned value.

So, basically, you could write:

$buffer = fgets($handle, 4096);
while ($buffer !== false) {
    echo $buffer;

    $buffer = fgets($handle, 4096);
}

Here you would have the assignment on a separate line. Because in that case you need to duplicate the assignment, the assignment in the loop condition is preferred.

PS: The most common example for an assignment in a while loop is probably fetching rows from mysql:

while ($row = mysql_fetch_assoc($result)) {
    echo $row['firstname'] . ' ' . $row['lastname'];
}