PHP 7 New Operators

14th September 2015

This is the first in a short series of articles aimed at highlight some of the key new features in the upcoming release of PHP 7. Firstly i'm going to look at 2 new comparison operators that will be available known as the spaceship operator and the null coalesce operator.

Spaceship Operator

The spaceship operator is a three-way comparison which when given two variables A and B will determine if A > B, A = B or A < B. In earlier versions of PHP this would require multiple comparisons to achive the same desired result

// if A is greater we want to return 1
// if B is greater we want to return -1
// if A and B are the same we want to return 0

// using php 5
($a < $b) ? -1 : (($a > $b) ? 1 : 0)

// using php 7
$a <=> $b

The operator isn't restricted to numeric values either, it will also work with other day types, for example with strings

echo "a" <=> "a"; // 0
echo "a" <=> "b"; // -1
echo "b" <=> "a"; // 1

Null Coalesce Operator

The null coalesce operator can come in very handy behaving like shorthand for the ternary operator. It will return the left hand side of the operator if the value is not null otherwise it will return the right side. Statements can be chained together so it essentially operates left to right finding the first non-null value.

In PHP 5 it's common to check a variable is set before assigning it to something then if it's not set we use a default value. This can be simplied in PHP 6 using this new operator.

// using php 5
$comment = isset($_GET['comment']) ? $_GET['comment'] : 'no comment';

// using php 7 null coalesce operator
$comment = $_GET['comment'] ?? 'no comment';

// chained example
$comment = $_GET['comment'] ?? $this->comment ?? $this->settings->default_comment ?? 'no comment';