PHP uksort

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

PHP: uksort() function

PHP: Sort an array by keys using a user-defined comparison function

The uksort() function is used to sort an array by the element keys 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.

Note: If two members compare as equal, their relative order in the sorted array is undefined.

Version

(PHP 4 and above)

Syntax

uksort(array_name, user_defined_function)

Parameters

Name

Description

Required /
Optional

Type

array_name

The input array.

Required

Array

user_defined_function

User supplied function.

Required

-

Return value

TRUE on success or FALSE on failure.

Value Type : Boolean.

Pictorial Presentation :

php array uksort() function

Example :

  1. function my_sort($x, $y)  

  2. {  

  3. if ($x == $y) return 0;  

  4. return ($x > $y) ? -1 : 1;  

  5. }  

  6. $people = array("10" => "javascript",  

  7. "20" => "php", "60" => "vbscript",  

  8. "40" => "jsp");  

  9. uksort($people, "my_sort");  

  10. print_r ($people);  

  11. ?>  

Output :

Array ( [60] => vbscript [40] => jsp [20] => php [10] => javascript )

Practice here online :