HomeMenu
Jesus · Bible · HTML · CSS · JS · PHP · SVG · Applications

uasort

Description

The uasort of Array for PHP sorts an array by values with an index association using a user-defined comparison function.

Syntax

 uasort(
    array &$array,
    callable $callback
): true

Parameters

array

The input array.

callback

The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.

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

first argument

b

second argument

CAUTION: Returning non-integer values from the comparison function, such as float, will result in an internal cast to integer of the callback's return value. So values such as 0.99 and 0.1 will both be cast to an integer value of 0, which will compare such values as equal.

Return

Returns true.

Examples

1 · array callback · ascending

<?

function callback($a, $b)
{
    return $a <=> $b;
}

$array =
[
    "e" => 2,
    "a" => 4,
    "c" => -1,
    "d" => -9,
    "g" => 3,
    "b" => 8,
    "f" => 5,
    "h" => -4
];
$callback = "callback";

uasort($array, $callback);

print_r($array);
Array
(
    [d] => -9
    [h] => -4
    [c] => -1
    [e] => 2
    [g] => 3
    [a] => 4
    [f] => 5
    [b] => 8
)

2 · array callback · descending

<?

function callback($a, $b)
{
    return $b <=> $a;
}

$array =
[
    "e" => 2,
    "a" => 4,
    "c" => -1,
    "d" => -9,
    "g" => 3,
    "b" => 8,
    "f" => 5,
    "h" => -4
];
$callback = "callback";

uasort($array, $callback);

print_r($array);
Array
(
    [b] => 8
    [f] => 5
    [a] => 4
    [g] => 3
    [e] => 2
    [c] => -1
    [h] => -4
    [d] => -9
)