What if you could compare values with just one simple symbol instead of many lines of code?
Why Spaceship operator in PHP? - Purpose & Use Cases
Imagine you need to compare two numbers to decide which one is bigger, smaller, or if they are equal. Doing this manually means writing multiple if-else statements to check each case.
Writing many if-else checks is slow and easy to mess up. It makes your code longer, harder to read, and more likely to have mistakes when comparing values.
The spaceship operator lets you compare two values in one simple step. It returns -1, 0, or 1 depending on whether the first value is less than, equal to, or greater than the second. This makes your code cleaner and easier to understand.
$a = 5; $b = 10; if ($a < $b) { return -1; } elseif ($a > $b) { return 1; } else { return 0; }
return $a <=> $b;It enables quick and clear comparisons that simplify sorting and decision-making in your code.
When sorting a list of scores, the spaceship operator helps decide the order of each pair quickly and cleanly.
Manual comparisons require many if-else statements.
Spaceship operator returns -1, 0, or 1 in one step.
This makes code shorter, clearer, and less error-prone.