PHP usort

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

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.

Pictorial Presentation :

php array usort() function

Example :

  1. function user_compare($x, $y)  

  2. {  

  3. if ($x == $y)  

  4. return 0;  

  5. else if ($x > $y)  

  6. return 1;  

  7. else  

  8. return -1;  

  9. }  

  10. $array1 = array(22,33,66,55,11);  

  11. usort($array1, 'user_compare');  

  12. foreach($array1 as $key => $value)  

  13. {  

  14. echo "$key: $value ";  

  15. }  

  16. ?>  

Output :

0: 11 1: 22 2: 33 3: 55 4: 66

Practice here online :