php - !$variable = $variable inside if
I was gnawing on the basics of PHP socket servers and client here.
Then I stumbled upon these lines (excerpt from the above links first example, happens insidewhile
):
if (false === ($buf = socket_read($msgsock, 2048, PHP_NORMAL_READ))) {
echo "socket_read() failed: reason: " . socket_strerror(socket_last_error($msgsock)) . "\n";
break 2;
}
if (!$buf = trim($buf)) {
continue;
}
I'm okay with the reading part, and closing connection in case there was an error reading.
But that nextif
is driving me nuts.
Firstly, I'm confused about how one may and would need to assign a value to boolean.
Secondly, I have trouble understanding the whole expression altogether.
Could someone please explain what happens inside that if, and how it applies to the server context?
P.S. Please excuse me if the question isn't properly asked. I'm just too confused about what happens there and have no idea what specifically to ask for.
Answer
Solution:
With this statement, there's no assignment to a boolean. We're comparing the type of
false
and the value offalse
(true false, not merely 0). You can read about that hereThen
This is the same as
So, to explain the original:
Answer
Solution:
Here's the explanation of the code.
First,
socket_read
is called, and the result is stored in$buf
. Then$buf
is compared withfalse
to see whether or not it is abool
and its value isfalse
. (===
means same type and equality at the same time)In this part of the code, first
$buf
is trimmed and the result is stored in$buf
. Then it's checked whether or not the$buf
isfalse
. If it is false,continue
takes action.Answer
Solution:
The expression is splitable.
$buf = trim($foo)
$check = !$buf
if ($check) { something(); }
first you get the variable, then check wether it evaluates to false (might be
false
, might benull
might be0
), and lastly oyu do the switch based on that information.Answer
Solution:
if you are seeking basics have a journey!
try this code
output