Tag Archives: PHP 7

PHP 7.4 – Null Coalesce Assignment Operator

PHP 7.4 added a new Null Coalesce Assignment Operator (??=) which is an enhancement of Null Coalesce Operator (??) introduced in PHP 7. The Null Coalesce Assignment Operator (??=) assigns the value of the right-hand parameter if the left-hand parameter is null. If the left-hand parameter is not null then its value is not changed. The Null Coalesce Assignment Operator is sometimes also called as Null Coalesce Equal Operator.

The Null coalesce operator (??) was added so that instead of using isset() along with the ternary operator (?:) we could just use the null coalesce operator (??). Here is an example usage:

// Fetches the value of $_GET['user'] 
// and returns 'nobody' if it does not exist.
$_GET['user'] = $_GET['user'] ?? 'nobody';
// This is equivalent to:
$_GET['user'] = isset($_GET['user']) ? $_GET['user'] : 'nobody';

The Null Coalesce Assignment Operator can now simplify the above statement even further as follows:

$_GET['user'] ??= 'nobody';

This operator is useful if you can checking if the value of variable is null and want to assign it some other value in that case. However, this operator does not works if you are trying to assign the values to a different variable. So, for example in the following case you cannot use the Null Coalesce Assignment Operator, but you can still use Null Coalesce Operator.

$username = $_GET['user'] ?? 'nobody';

More reading:
PHP RFC: Null Coalescing Assignment Operator
Null Coalesce Operator (??)

PHP 7 – Combined Comparison (Spaceship) Operator

In this post we will take a look and another new operator in PHP 7. This operator is the Combined Comparison or Spaceship operator (<=>). This operator is a three way comparison operator. It will do greater-than, less-than and equal comparisons between two operands.

The spaceship operator (<=>) returns -1 if the left side is smaller, 0 if the values are equal and 1 if the left side is larger. It can be used on all generic PHP values with the same semantics as < , <=, ==, >=, >. This operator is similar in behavior to strcmp() or version_compare(). This operator can be used with integers, floats, strings, arrays, objects, etc.
Read more »

PHP 7 – Null Coalesce Operator

PHP 7 brings a lot of improvements, features and new operators as compared to the earlier versions on PHP. One of the new operators is the Null Coalesce Operator (??). This operator can be used instead of using isset() along with the ternary operator (?:).

The Null coalesce operator (??) returns the result of its first operand if it exists and is not NULL, or else it will return its second operand. Using this operator like $_GET[‘mykey’] ?? “” will not raise an E_NOTICE, and can be safely used.
Read more »