Search code examples
ternary-operatorspaceship-operatorphp-7

How will comparison operators (spaceship operator) be handled in ternary operators


This question is a little preemptive, as php 7 is not even released yet. I'm curious how the spaceship operator will be handled in the context of ternary operators.

so if I have a pre-spaceship ternary expression such as:

$foo = 1;
$bar = 0;
echo 'foo is ' . ( ($foo > $bar) ? 'greater than' : ( ($foo < $bar ) ? 'less than' : 'equal to' ) ) . ' bar.';

what would be the equivalent ternary operator using a comparison operator? Are ternaries going to have some means of handling this scenario? I use ternary operators quite a lot and am curious if there is some way to streamline the code in various instances where a comparison operator would be relevant.


Solution

  • The spaceship operator, as you can see from the documentation of its RFC, was though mainly to be used when having to deal with orderings.

    I don't think it could be of help in shortening the code that you posted, mainly beacuse the ternary operator expects a boolean value and the ternary operator returns a "true" value (1 and -1) in both cases when the the values are different. In other words, when you cast its return value to a boolean, the spaceship operator is equivalent to the != operator.

    Anyway, you could experiment with it on 3v4l.org, like I did here