The usort Function
The usort
function sorts an array
by element values, using a
callback to determine the order
of elements in the sorted array.
The function modifies the array itself.
The comparison function must return an integer, which depending on the comparison result: less than, equal to, or greater than zero.
Syntax
usort(array &$array, callable $callback): bool
Example
Let's sort an array in ascending order of elements:
<?php
$arr = [1, 3, 2, 5, 4];
function func($a, $b)
{
if ($a === $b) {
return 0;
} else if ($a < $b) {
return -1;
} else {
return 1;
}
}
usort($arr, 'func');
var_dump($arr);
?>
Code execution result:
[1, 2, 3, 4, 5]
Example
Now let's sort an array in descending order of elements:
<?php
$arr = [1, 3, 2, 5, 4];
function func($a, $b)
{
if ($a === $b) {
return 0;
} else if ($a > $b) {
return -1;
} else {
return 1;
}
}
usort($arr, 'func');
var_dump($arr);
?>
Code execution result:
[1, 2, 3, 4, 5]
Example
Now let's sort an array by ascending number of characters in the array elements:
<?php
$arr = [
'123',
'1',
'12345',
'12',
'1234',
];
function func($a, $b)
{
if (strlen($a) === strlen($b)) {
return 0;
} else if (strlen($a) < strlen($b)) {
return -1;
} else {
return 1;
}
}
usort($arr, 'func');
var_dump($arr);
?>
Code execution result:
[
'1',
'12',
'123',
'1234',
'12345',
]
See Also
-
the
sort
function,
which sorts by element values in ascending order -
the
rsort
function,
which sorts by element values in descending order -
the
ksort
function,
which sorts by keys in ascending order -
the
krsort
function,
which sorts by keys in descending order -
the
asort
function,
which sorts by element values in ascending order, preserving keys -
the
arsort
function,
which sorts by element values in descending order, preserving keys -
the
natsort
function,
which sorts using natural order -
the
natcasesort
function,
which sorts using natural order, case-insensitive -
the
usort
function,
which sorts using a callback -
the
uksort
function,
which sorts by keys using a callback -
the
uasort
function,
which sorts using a callback, preserving keys -
the
array_multisort
function,
which sorts multiple arrays