Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

evaluation of assignment in php

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?

like image 502
user151841 Avatar asked May 09 '11 17:05

user151841


People also ask

What does PHP assignment return?

Summary. Use PHP assignment operator ( = ) to assign a value to a variable. The assignment expression returns the value assigned.

What does => mean in PHP?

It means assign the key to $user and the variable to $pass. When you assign an array, you do it like this. $array = array("key" => "value"); It uses the same symbol for processing arrays in foreach statements. The '=>' links the key and the value.

What is the use of assignment operator?

The assignment operator = assigns the value of its right-hand operand to a variable, a property, or an indexer element given by its left-hand operand. The result of an assignment expression is the value assigned to the left-hand operand.


1 Answers

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'];
}
like image 75
NikiC Avatar answered Sep 27 '22 23:09

NikiC