In Python3.8 There is new operator called walrus (:=) which can assign new variables inside a condition. I write a simple TCP socket connection in PHP, and I want my program to look nicer.
Is there something similar to it in PHP: Hypertext Preprocessor ?
if ($data := socket_read ($socket, 1024)) {
echo $data;
}
This works if the return value of socket_read() is "thruthy" or "falsy".
Falsy is '', 0, [], null or false.
Truthy is anything else.
if ( $data = socket_read($socket, 1024) ) {
echo $data;
}
And if you want to be more specific you can even do the following (credits to @Benni):
if ( 'foo' === $data = socket_read($socket, 1024) ) {
echo 'data equals foo';
}
Or
if ( is_array($data = socket_read($socket, 1024) ) {
var_dump($data);
}
Your example might throw an exception if you are not sure socket_read() returns a string.
In that case you can do the following:
if ( is_string($data = socket_read($socket, 1024)) ) {
echo $data;
}
For more information about PHP boolean behaviour see https://www.php.net/manual/en/language.types.boolean.php
I thought I'd try and add a bit more context to this, maybe someone else will find it useful in future.
The reason PHP doesn't have (or more importantly, need) a walrus operator is that in PHP, the assignment operator = is both a statement and an expression.
When you write
$var = 'foo';
not only are you assigning the value foo to $var, but the statement as a whole evaluates to it:
php > var_dump($var = 'foo');
string(3) "foo"
Using = in a PHP condition isn't some magical overriding of the operator in that context, it's just a natural side effect of the fact that an assignment is also an expression.
In Python, this isn't the case. The assignment operator (again, =) is only a statement. It doesn't itself have a result, and so can't be used in a condition. The walrus operator was added in v3.8 (as mentioned in the question), as a way to bridge that gap. There's a lot more discussion about this in the questions Can we have assignment in a condition? and “:=” syntax and assignment expressions: what and why?.
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