PHP usort array function

Last Updated: February 21, 2022

usort – Sort an array by value using user-defined functions

Syntax

usort(array &$array, callable $callback): bool

Supports (PHP 4 , PHP 5, PHP 7, PHP 8)

Parameters

Parameter Description
array input array
callback

Callback function used for sorting

callback(mixed $a, mixed $b): int

Return Value

Always return true

Example

function cmp($a, $b) {
    if ($a == $b) {
        return 0;
    }
    return ($a < $b) ? -1 : 1;
}

$array1 = array("a"=>'One',"c"=> 'Three',"b"=>'Two');

usort($array1,"cmp");
print_r($array1);

Output

Array ( [0] => One [1] => Three [2] => Two )

Test