# usort

Sort an array by values using a user-defined comparison function

## Syntax

`usort ( array &\$array , callable \$value_compare_func ) : bool`

### Parameters

`array`

The input array.

`value_compare_func`

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`

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 on success or FALSE on failure.

## 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);
\$value_compare_func = "myfunction";

usort(\$array, \$value_compare_func);

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";
\$value_compare_func = "myfunction";

usort(\$array, \$value_compare_func);

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");
\$value_compare_func = array("myclass", "myfunction");

usort(\$array, \$value_compare_func);

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');
\$value_compare_func = myfunction('key_b');

usort(\$array, \$value_compare_func);

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

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