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?
Summary. Use PHP assignment operator ( = ) to assign a value to a variable. The assignment expression returns the value assigned.
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.
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.
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'];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With