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

usort

Description

The usort of Array for PHP sort an array by values using a user-defined comparison function.

Syntax

usort(
    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

Always returns true.

Examples

1

<?

function myfunction($a, $b)
{
    if($a < $b)
    {
        return -1;
    }
    else if($a > $b)
    {
        return 1;
    }
    else
    {
        return 0;
    }
}

$array = array(3, 2, 5, 6, 1);
$callback = "myfunction";

usort($array, $callback);

print_r($array);

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

2

<?

function myfunction($a, $b)
{
    return strcmp($a, $b);
}

$array[0] = "lemons";
$array[1] = "apples";
$array[2] = "grapes";
$callback = "myfunction";

usort($array, $callback);

foreach($array as $key => $value)
{
    echo "\$array[$key]: $value\n";
}

?>
$array[0]: apples
$array[1]: grapes
$array[2]: lemons

3

<?

class myclass
{
    var $name;

    function __construct($name)
    {
        $this->name = $name;
    }

    static function myfunction($a, $b)
    {
        $al = strtolower($a->name);
        $bl = strtolower($b->name);

        if($al == $bl)
        {
            return 0;
        }

        return ($al > $bl) ? 1 : -1;
    }
}

$array[] = new myclass("c");
$array[] = new myclass("b");
$array[] = new myclass("d");
$callback = array("myclass", "myfunction");

usort($array, $callback);

foreach($array as $item)
{
    echo $item->name . "\n";
}

?>
b
c
d

4

<?

function myfunction($key)
{
    return function($a, $b) use ($key)
    {
        return strnatcmp($a[$key], $b[$key]);
    };
}

$array[0] = array('key_a' => 'z', 'key_b' => 'c');
$array[1] = array('key_a' => 'x', 'key_b' => 'b');
$array[2] = array('key_a' => 'y', 'key_b' => 'a');
$callback = myfunction('key_b');

usort($array, $callback);

foreach($array as $item)
{
    echo $item['key_a'] . ', ' . $item['key_b'] . "\n";
}

?>
y, a
x, b
z, c
HomeMenu