PHP 7 interview question · Most asked

What does the spaceship operator `<=>` return and where is it used?

Summary

$a <=> $b returns -1, 0 or 1 when $a is less than, equal to, or greater than $b, which makes it ideal for usort comparators.

Longer Answer

It works on integers, floats, strings and arrays using PHP's standard comparison rules. For multi-key sorts, compare arrays: [$a->last, $a->first] <=> [$b->last, $b->first].

Code Example

<?php
usort($people, fn($a, $b) => [$a['last'], $a['first']] <=> [$b['last'], $b['first']]);
// before 7.4 arrow functions:
usort($nums, function ($a, $b) { return $b <=> $a; }); // descending

Key Points

  • Returns -1, 0, or 1
  • Perfect for usort/uasort callbacks
  • Compare arrays for multi-column sorting

More most-asked PHP 7 questions

← All PHP 7 questions