[PHP] Sort an array with usort

Created on November 28, 2026

You can use the usort function to sort array elements by a custom comparison and update the original array in place. Pass a comparison callback as the second argument; the callback returns a negative integer, zero, or a positive integer to define the order.

This example sorts numbers in ascending order.

<?php

$nums = [3, 1, 4, 1, 5];
usort($nums, fn($a, $b) => $a <=> $b);
print_r($nums);

The script produces the following output.

Array
(
    [0] => 1
    [1] => 1
    [2] => 3
    [3] => 4
    [4] => 5
)

usort reindexes the array from 0 after sorting. If you need to sort values while preserving keys, you can use uasort. When every element is numeric and you only need simple ascending or descending order, sort or rsort may be enough.

References

PHP