Introduction

This RFC adds a new operator for combined comparison. Similar to strcmp() or version_compare() in behavior, but it can be used on all generic PHP values with the same semantics as <, <=, ==, >=, >.

Proposal

Add a new operator (expr) <=> (expr), it returns 0 if both operands are equal, 1 if the left is greater, and -1 if the right is greater. It uses exactly the same comparison rules as used by our existing comparison operators: <, <=, ==, >= and >. (See the manual for details)

This "three-way comparison operator", also known as the “spaceship operator” (a common name in other languages), works on all standard PHP values. It exists in other languages: Perl, Ruby, and Groovy.

It is implemented by using the result of the existing internal compare_function that underlies the other comparison operators. The existing comparison operators could be considered mere shorthands for <=>:

if(($handle=fopen("people.csv","r"))!==FALSE){while(($row=fgetcsv($handle,1000,","))!==FALSE){$data[]=$row;}fclose($handle);}// Sort by last name:usort($data,function($left,$right){return$left[1]<=>$right[1];});

Usefulness

It makes writing ordering callbacks for use with usort() easier. Commonly, users write poor or incorrect ordering functions like this one:

function order_func($a,$b){return$a>=$b;}

When users do write correct ordering functions, they have to be quite verbose:

function order_func($a,$b){return($a<$b) ? -1:(($a>$b) ? 1:0);}

This becomes particularly bad when sorting by multiple columns lexicographically.

With this operator, you can easily write proper ordering functions, like this one:

Backward Incompatible Changes

Proposed PHP Version(s)

New Constants

A T_SPACESHIP constant for use with ext/tokenizer has been added.

Unaffected PHP Functionality

All existing comparison operators are unaffected by this addition.

Future Scope

None.

Vote

Voting started on 2015-02-02 and will to end on 2015-02-16. As this adds to the PHP language (and hence affects the PHP language specification) a 2/3 majority is required for acceptance. It is a Yes/No vote to accepting the RFC and merging the patch.