Search code examples
phpphp-7

What is the difference between strcmp() and Spaceship Operator (<=>)


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?


Solution

  • 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