Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / PHP

Sorting and comparison

A comparison callback must return an integer below zero, zero or above zero.

Version: PHP 8.4; repository runtime, production runtime not attested

Syntax

usort($rows, fn($a, $b) => $a["rank"] <=> $b["rank"]);

A comparison callback must return an integer below zero, zero or above zero. The spaceship operator expresses this order without subtracting potentially large values. usort modifies the array and assigns new integer keys. Since PHP 8 equal elements retain their previous relative order.

$rows=[9=>["A",2],4=>["B",1],2=>["C",2]];usort($rows,fn($a,$b)=>$a[1]<=>$b[1]);echo json_encode([array_column($rows,0),array_keys($rows)]);
[["B","A","C"],[0,1,2]]

Examples

<?php
$rows=[9=>["A",2],4=>["B",1],2=>["C",2]];usort($rows,fn($a,$b)=>$a[1]<=>$b[1]);echo json_encode([array_column($rows,0),array_keys($rows)]);

Result

[["B","A","C"],[0,1,2]]

Sources