Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 790
Andre Avatar asked May 11 '16 16:05

Andre


1 Answers

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

like image 145
Maxim Tkach Avatar answered Sep 28 '22 03:09

Maxim Tkach