sajad torkamani

The spaceship operator is used to compare two values and return an integer based on the comparison result. It’s typically used when implementing a custom sort function.

For example, given the below code:

$result = $a <=> $b;

$result will be:

  • -1 if the left-hand operand ($a) is less than the right-hand operand ($b).
  • 0 if $a and $b are equal.
  • 1 if $b is greater than $a.

The above code is equivalent to:

if ($a < $b) {
    return -1;
} elseif ($a == $b) {
    return 0;
} else {
    return 1;
}
Tagged: PHP