🐘 PHP Beginner

What is the spaceship operator in PHP?

Why Interviewers Ask This

Interviewers use this question to quickly assess whether a candidate has the foundational knowledge required for PHP development. It reveals whether you understand the building blocks that more complex concepts rely on.

Answer

The spaceship operator (<=>), introduced in PHP 7, is a three-way comparison operator that returns -1, 0, or 1 — negative if the left side is less than the right, 0 if equal, positive if greater. It works on integers, floats, strings, arrays, and objects. It is primarily used in sorting callbacks: usort($people, fn($a, $b) => $a["age"] <=> $b["age"]); — this concisely replaces the old pattern of comparing values and returning -1, 0, or 1 manually. For descending sort, swap the operands: $b["age"] <=> $a["age"]. The name "spaceship" comes from the resemblance of <=> to a UFO.

Pro Tip

Before answering, structure your response: one-line definition → real-world analogy → concrete example from a project. This makes even complex PHP answers easy to follow.