Reaching for the Stars

27 03 2016

Flickr: by OblongFlickr: by Oblong

In 2014, Davey Shafik, author of the Zend PHP 5 Certification Study Guide, presented a proposal to the PHP Internals List recommending the addition of yet another operator, the spaceship. While the operator’s name may connote PHP blasting off, its down-to-earth function scarcely relates to outer space.

 

Operating without Lift-Off

The spaceship moniker originates from the operator’s appearance; its characters combine seemingly to resemble a space vehicle, as follows:

<=>

The spaceship or combined comparison operator, another term, offers a pragmatic way to facilitate comparisons for numbers, strings and even objects. Just as strcmp() employs three-valued logic, so too does this operator depending on whether the leftmost operand is respectively less than, equal to, or greater than the rightmost operand. For more details, you may wish to review the combined comparison RFC (“Request for Comments”, a designation for the formal proposal) and the Manual, including this section.

 

Ice Cream Flavored Progress

The spaceship operator already appears in popular languages such as Ruby and Groovy, so its inclusion in PHP seems befitting for both injecting some coolness and practical functionality. If ice cream flavors may denote progress, then this operator surely met with a “Rocky Road.” Initially, Shafik proposed the operator for PHP 5.6 but it failed to gain traction, in part apparently because of poor timing. A newly adopted rule determined that features could be added until PHP 5.6 alpha. When Shafik made his proposal , PHP 5.6 alpha2 had already been released, so it regrettably failed to meet the deadline.

Andrea Faulds liked Shafik’s proposal and with his permission, she subsequently revived the RFC, reworking it for inclusion in PHP 7. She announced the revised proposal in January 2015 and a more productive discussion ensued, followed by a vote the next month. Astonishingly, in the midst of the vote, Faulds abruptly quit the Internals List and sought to withdrew the RFC.

At this point, imagine someone singing the hit song from Pinocchio, “When You Wish Upon a Star”, and focus on the following verse:

Like a bolt out of the blue
Fate steps in and sees you through
When you wish upon a star
Your dreams come true

A prominent member of the PHP Internals List, Stanislav Malyshev, rose to the occasion and assumed authorship of the spaceship RFC, thereby enabling the vote to continue. This fortuitous circumstance caused the RFC to pass with 43 in favor and only 11 opposed, a vote which exceeded the required 2/3 majority. And, on a parenethical note, Faulds would later rejoin the PHP project in November 2015.

 

Pros and Cons

The combined comparison operator derives from Perl, so its introduction makes PHP a bit more Perlish which some might find distasteful. If a feature is truly a laudable one but might diminish the essential nature of PHP, is it really wise to include it? But, this operator enhances PHP just as it does Perl. In both languages it provides a handy way to sort numbers quickly. In PHP, it’s especially beneficial when used with usort(), as follows:

<?php

$arr = array(2,3,1,5,4,9,6,8,7);
function cmp($a,$b){
    return $a <=> $b;
}
usort($arr,"cmp");
print_r($arr);
/**
   *   Array
   *   (
   *   [0] => 1
   *   [1] => 2
   *   [2] => 3
   *   [3] => 4
   *   [4] => 5
   *   [5] => 6
   *   [6] => 7
   *   [7] => 8
   *   [8] => 9
   *   )
**/

See https://3v4l.org/HHcYE

The main advantage of the spaceship operator is that it lends itself to writing far less code. If you wish to determine whether two numbers are equivalent, or whether one is greater or inferior to the other, the binary operator along with its operands most satisfactorily suffices, as evident in this next example:

$a = 10;
$b = 5;
echo $a <=> $b;   // 1

See livecode here.

The code relies on the internal compare_function(), which contains the following ternary expression:


ZVAL_LONG(result, Z_LVAL_P(op1)>Z_LVAL_P(op2)?1:(Z_LVAL_P(op1)<Z_LVAL_P(op2)?-1:0));

See PHP 7 – zend_operators.c

The internal source code saves the user from the tedium of writing a similar ternary expression in PHP in order to test the values of two operands in relation to each other. The Manual confirms that the results will be a number whose value is -1, 0, or 1. Oddly, in another section of the Manual the return value is less specific:

An integer less than, equal to, or greater than zero when $a is respectively less than, equal to, or greater than $b.

Note, this last description echos that of strcmp().

 

Mystery!

To momentarily deviate from the beaten track, one may well wonder how the compare_function() comes into play. Unsurprisingly, the handler for the spaceship opcode invokes it, but where may one view that opcode? If you peruse the opcode dump portrayed by the well-respected VLD (“Vulcan Logic Dumper” or more formally as “The Vulcan Logic Disassembler”), it fails to appear in the opcode listing! This circumstance results from PHP 7’s AST (Abstract Syntax Tree) generating this opcode instead of traditionally the parser (see here for explanation).

 

Final Note

The spaceship operator from the name to its appearance and functionality is a welcome and fun addition to PHP. It should elicit a smile by merely uttering its name. Once upon a time users loved PHP and delighted in its fun, i.e. phun approach to computer programming. Recent years have seen a greater emphasis on regulating PHP for consistency and including features based on high level computer concepts. Along with the unofficial mascot, the cuddly ElePHPant available in an ever-increasing rainbow of colors, the spaceship operator should help restore the balance between regarding PHP seriously and yet still enjoying the bit of phun it brings to PHP. Critics may argue that PHP still has its share of imperfection but to quote Bette Davis in the film “Now Voyageur”:

Oh, Jerry, don’t let’s ask for the moon. We have the stars.

Wikipedia

Who knows, the starship operator may delight some developers to the extent of feeling “over the moon.” 🙂

 

Update

Recently, Nikita Popov proposed that for the sake of consistency a spaceship assignment operator should form part of PHP, as follows:

<?php

$a <=>= $b;
// same as
$a = ($a <=> $b); 

PHP Internals List March 24, 2016

So, far this idea has failed to gain much support. In fact, core contributor Dmitry Stogov probably says it best:

I hope this is a joke.
Lets try not to reinvent Perl.

PHP Internals List March 24, 2016

Suggested Reading

This work is licensed under a Creative Commons License

Advertisements

Actions

Information

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s




%d bloggers like this: