5

In PHP 7 we have a new operator, spaceship operator <=>, and I found it very similar (if not the same) to strcmp().

Is there any difference between them?

Edit: Im asking the difference between them both, not refered What is <=> (the 'Spaceship' Operator) in PHP 7? or What is <=> (the 'Spaceship' Operator) in PHP 7?

Community
  • 1
  • 1
Andre
  • 5,291
  • 4
  • 27
  • 38
  • 1
    Possible duplicate of [What is <=> (the 'Spaceship' Operator) in PHP 7?](http://stackoverflow.com/questions/30365346/what-is-the-spaceship-operator-in-php-7) – Marcos Pérez Gude May 11 '16 at 16:17
  • From the [RFC](https://wiki.php.net/rfc/combined-comparison-operator) `Similar to strcmp() or version_compare() in behavior, but it can be used on all generic PHP values with the same semantics as =, >.`. – Jonnix May 11 '16 at 16:18
  • @MarcosPérezGude ive saw that one and does not answer my question. my question is what is the difference, and I do not see any ref to it. – Andre May 11 '16 at 16:20
  • 1
    `strcmp` compares strings, `<=>` compares different datatypes. – u_mulder May 11 '16 at 16:24
  • Ok, sorry, i retract my vote – Marcos Pérez Gude May 11 '16 at 16:36

2 Answers2

4

strcmp - it is function for "binary safe" string comparison

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.

For example you can compare arrays or objects, and by float you get different result:

$var1 = 1.3;
$var2 = 3.2;
var_dump($var1 <=> $var2); // int(-1)
var_dump(strcmp($var1, $var2)); // int(-2)

And other differences...

More example this

Maxim Tkach
  • 1,557
  • 11
  • 23
0

According to the official document:

"<=>" returns "an integer less than, equal to, or greater than zero" while "strcmp" retuens "<0 , =0 or >0", so you may not find any difference there.

And usually, this is enough because we don't care what exact value is returned, but, something is revealed as below:

echo 5 <=> 1; // 1
echo strcmp(5,1); // 4

I could never get values other than 1,0,-1 from spaceship.

John Lee
  • 29
  • 2