LearnThatStack Ace your next interview
PHP · question
Question 11 of 82

Explain the spaceship operator in PHP.

beginner
← All PHP questions
Re-explain

The spaceship operator <=> is a three-way comparison operator. It returns -1 when the left side is smaller, 0 when both sides are equal, and 1 when the left side is greater. PHP 7.0 introduced it.

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

It follows PHP's usual comparison rules, so it works on numbers, strings and arrays. Its main use is sorting callbacks, because usort() expects exactly this kind of result. For example, usort($users, fn($a, $b) => $a->age <=> $b->age) sorts users by age.

It also compares several values at once. Comparing arrays, as in [$a->last, $a->first] <=> [$b->last, $b->first], sorts by last name and then by first name. Swap $a and $b to sort in descending order.

Rewriting in plainer words…

This answer doesn't lend itself to a diagram - it reads best . No credits were charged.

Why there's no diagram: “”

The interactive diagram is below the answer - jump to diagram ↓ · Below it, the related concept . Jump to it ↓

The diagram below the answer is the concept . Jump to it ↓

Tailored explanation · switch back to · ·
What should the new diagram focus on?
How well did you know this?
AI:

Saved in this browser - sign in to keep your review list.

How should your speech become text?

Listening… your words appear above as you speak - tap Stop when you're done.

Recording · cr - tap Stop & transcribe when you're done.

Transcribing with AI…

Voice:

Keep going - a few more words and AI can grade it.

Interview lens

Likely follow-ups, what you can say, and the weak answers to avoid.

Sign in free to open it Free account - the lens opens as soon as you're back.

Want a quick review of the fundamentals? See the PHP cheatsheet.

← Back to all PHP questions
Pro · $10/mo

71 of 82 PHP answers are in Pro.

Full answers, code samples, and AI explanations that go simpler or deeper. Cancel anytime.

  • Full answers + code
  • AI explanations, simpler or deeper
  • 1,000 AI credits / month
  • Cancel anytime