DEV Community

thiCha
thiCha

Posted on

1

Spaceship operator 🚀 in PHP

Introduced in PHP 7, the Spaceship operator <=> is used to compare two expressions.

It returns:

  • 0 if both values are equal
  • 1 if left operand is greater
  • -1 if right operand is greater

Let’s see it with an example:

echo 2 <=> 2; // Outputs 0
echo 3 <=> 1; // Outputs 1
echo 1 <=> 3; // Outputs -1

echo "b" <=> "b"; // Outputs  0
echo "a" <=> "c"; // Outputs -1
echo "c" <=> "a"; // Outputs 1

// Note: for string comparison, the ASCII value of the characters are used, that is why "c" is greater than "a"
echo "ping" <=> "pong"; // Outputs -1 since "o" is greater than "i"
Enter fullscreen mode Exit fullscreen mode

This operator can be used for sorting arrays:

$numbers = [1, 4, 5, 9, 2, 3];

usort($numbers, function ($a, $b) {
    return $a <=> $b; // Sort in ascending order
});

echo print_r($numbers); // Outputs [1,2,3,4,5,9]

usort($numbers, function ($a, $b) {
    return $b <=> $a; // Sort in descending order
});

echo print_r($numbers); // [9,5,4,3,2,1]
Enter fullscreen mode Exit fullscreen mode

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

đź‘‹ Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay