0
0
PHPprogramming~5 mins

Spaceship operator in PHP

Choose your learning style9 modes available
Introduction

The spaceship operator helps compare two values quickly and clearly. It tells you if one value is less than, equal to, or greater than the other.

When you want to sort a list of numbers or strings.
When you need to compare two values and know their order.
When writing custom comparison functions for sorting.
When you want a simple way to check if one value is smaller, equal, or bigger than another.
Syntax
PHP
$result = $a <=> $b;

The operator is written as <=>.

It returns -1 if $a is less than $b, 0 if they are equal, and 1 if $a is greater than $b.

Examples
3 is less than 5, so the result is -1.
PHP
$result = 3 <=> 5; // returns -1
7 equals 7, so the result is 0.
PHP
$result = 7 <=> 7; // returns 0
10 is greater than 2, so the result is 1.
PHP
$result = 10 <=> 2; // returns 1
Sample Program

This program compares two numbers and prints if the first is less than, equal to, or greater than the second using the spaceship operator.

PHP
<?php
// Compare two numbers using spaceship operator
$a = 8;
$b = 12;
$result = $a <=> $b;

if ($result === -1) {
    echo "$a is less than $b";
} elseif ($result === 0) {
    echo "$a is equal to $b";
} else {
    echo "$a is greater than $b";
}
OutputSuccess
Important Notes

The spaceship operator works with numbers, strings, and other comparable types.

It is very useful in sorting functions where you need to return -1, 0, or 1.

Summary

The spaceship operator compares two values and returns -1, 0, or 1.

It makes comparison code shorter and easier to read.

Use it when you want to know the order between two values.