Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How the PHP spaceship operator <=> exactly works on strings?

I'am litte bit confused about the the functinning of the spaceship operator on string. In the documentation they say that comparisons are performed according to PHP's usual type comparison rules but not yet clear to me! I looked at this stackoverflow question and did some tests but still confused.

Here is the code I tested:

<?php

$str1 = "aaa";
$str2 = "aaaa";

echo $str1 <=> $str2, PHP_EOL; // -1

$str1 = "baaaaaa";
$str2 = "abbb";

echo $str1 <=> $str2, PHP_EOL; // 1

$str1 = "aaaaaaa";
$str2 = "bbbb";

echo $str1 <=> $str2, PHP_EOL; // -1

How it uses the ASCII values? Thank you for help.

like image 910
Houssem ZITOUN Avatar asked Sep 19 '25 14:09

Houssem ZITOUN


1 Answers

Compare two expressions.

For string it uses the ASCII values.

It returns -1, 0 or 1 when first expression is respectively less than, equal to, or greater than second expression.

// Integers
echo 1 <=> 1; // 0
echo 1 <=> 2; // -1
echo 2 <=> 1; // 1
 
// Floats
echo 1.5 <=> 1.5; // 0
echo 1.5 <=> 2.5; // -1
echo 2.5 <=> 1.5; // 1
 
// Strings
echo "a" <=> "a"; // 0
echo "a" <=> "b"; // -1
echo "b" <=> "a"; // 1
 
echo "a" <=> "aa"; // -1
echo "zz" <=> "aa"; // 1
 
// Arrays
echo [] <=> []; // 0
echo [1, 2, 3] <=> [1, 2, 3]; // 0
echo [1, 2, 3] <=> []; // 1
echo [1, 2, 3] <=> [1, 2, 1]; // 1
echo [1, 2, 3] <=> [1, 2, 4]; // -1
 
// Objects
$a = (object) ["a" => "b"]; 
$b = (object) ["a" => "b"]; 
echo $a <=> $b; // 0
 
$a = (object) ["a" => "b"]; 
$b = (object) ["a" => "c"]; 
echo $a <=> $b; // -1
 
$a = (object) ["a" => "c"]; 
$b = (object) ["a" => "b"]; 
echo $a <=> $b; // 1
 
// not only values are compared; keys must match
$a = (object) ["a" => "b"]; 
$b = (object) ["b" => "b"]; 
echo $a <=> $b; // 1
like image 123
Manash Kumar Avatar answered Sep 21 '25 06:09

Manash Kumar