Search code examples
phpphp-7string-comparison

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.


Solution

  • I read all the answers but it was insufficient for me as the topic for me is how PHP does things internally. So I searched and searched and it turns out that PHP uses the comparison with the operator <=> on strings, character by character and it stops when there is only one different character and this with ASCII codes as follows:

    <?php
    
    $str1 = "aaaaaaa";
    $str2 = "bbbb";
    
    echo $str1 <=> $str2, PHP_EOL; // -1
    
    print_r(unpack("C*", $str1));
    print_r(unpack("C*", $str2));
    
    
    // output
     Array
    (
        [1] => 97
        [2] => 97
        [3] => 97
        [4] => 97
        [5] => 97
        [6] => 97
        [7] => 97
    )
    Array
    (
        [1] => 98
        [2] => 98
        [3] => 98
        [4] => 98
    )
    

    which explains why $str1 <=> $str2 === -1.