PHP: usort() function
PHP: Sort an array by values using a user-defined comparison function
The usort() function is used to sort an array by its values using a user-defined comparison function. If the array you wish to sort needs to be sorted by some non-trivial criteria, you should use this function.
The function removes any existing keys and assigns new keys for the elements in the array.
Version:
(PHP 4 and above)
Syntax:
usort(array_name, user-defined-function)
Parameters:
Name | Description | Required / Optional |
Type |
---|---|---|---|
array_name | The specified array which will be sorted. | Required | Array |
user-defined-function | User define function. | Required | - |
Return value:
TRUE on success, or FALSE on failure.
Value Type: Boolean.
Example:
<?php
function user_compare($x, $y)
{
if ($x == $y)
return 0;
else if ($x > $y)
return 1;
else
return -1;
}
$array1 = array(22,33,66,55,11);
usort($array1, 'user_compare');
foreach($array1 as $key => $value)
{
echo "$key: $value\n";
}
?>
Sample Output:
0: 11 1: 22 2: 33 3: 55 4: 66
Pictorial Presentation:

View the example in the browser
Practice here online:
See also
Previous: uksort
Next: Calendar Functions cal_days_in_month
PHP: Tips of the Day
Filters the collection using the given callback
Example:
<?php function tips_reject($items, $func) { return array_values(array_diff($items, array_filter($items, $func))); } print_r(tips_reject(['Apple', 'Pear', 'Kiwi', 'Banana'], function ($item) { return strlen($item) > 4; })); ?>
Output:
Array ( [0] => Pear [1] => Kiwi )
- Weekly Trends
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join
- JavaScript functions Exercises
- Python Tutorial
- Python Array Exercises
- SQL Cross Join
- C# Sharp Array Exercises