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/uasortcallbacks - Compare arrays for multi-column sorting
More most-asked PHP 7 questions
- What are typed properties in PHP 7.4?
- What were the headline improvements of PHP 7.0 over PHP 5.6?
- Explain scalar type declarations and coercive vs strict mode in PHP 7.
- Explain the `Throwable`, `Error` and `Exception` hierarchy introduced in PHP 7.
- What are nullable types in PHP 7.1?
- How do return type declarations work in PHP 7?
- What does the null coalescing operator `??` do, and how is it different from `isset()` with a ternary?
- What are arrow functions in PHP 7.4 and how do they differ from closures?