3

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;
}

2 Answers2

5

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

jrswgtr
  • 2,079
  • 5
  • 14
  • 31
  • 1
    ... and when you want to be more specific, you can extend your expression like this: `if ('foo' === $data = socket_read($socket, 1024)) { ...` or even `if (is_array($data = socket_read($socket, 1024)) { ...` – Benni Aug 04 '20 at 11:59
  • Thanks @Benni. I added the examples to the answer! – jrswgtr Aug 04 '20 at 13:27
2

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?.

iainn
  • 15,089
  • 9
  • 27
  • 37