The uasort Function
The uasort
function sorts an array
in ascending order by elements, preserving
the keys of the associative array.
The uasort
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.
The function modifies the array itself.
Syntax
uasort(array &$array, int $flags = SORT_REGULAR): bool
Example
Let's sort the array in ascending order by elements:
<?php
$arr = [
'b' => 1,
'e' => 3,
'c' => 2,
'a' => 5,
'd' => 4,
];
function func($a, $b)
{
if ($a === $b) {
return 0;
} else if ($a < $b) {
return -1;
} else {
return 1;
}
}
uasort($arr, 'func');
var_dump($arr);
?>
Code execution result:
[
'b' => 1,
'c' => 2,
'e' => 3,
'd' => 4,
'a' => 5,
]
Example
Now let's sort the array by the number of characters in the array elements in ascending order:
<?php
$arr = [
'a' => '123',
'b' => '1',
'c' => '12345',
'd' => '12',
'e' => '1234',
];
function func($a, $b)
{
if (strlen($a) === strlen($b)) {
return 0;
} else if (strlen($a) < strlen($b)) {
return -1;
} else {
return 1;
}
}
uasort($arr, 'func');
var_dump($arr);
?>
Code execution result:
[
'b' => '1',
'd' => '12',
'a' => '123',
'e' => '1234',
'c' => '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 while preserving keys -
the
arsort
function,
which sorts by element values in descending order while preserving keys -
the
natsort
function,
which sorts using natural order -
the
natcasesort
function,
which sorts using natural order case-insensitively -
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 while preserving keys -
the
array_multisort
function,
which sorts multiple arrays