PHP - Function uasort()



uasort ( $array, $cmp_function )

Definition and Usage

This function sorts an array such that array indices maintain their correlation with the array elements they are associated with. This is used mainly when sorting associative arrays where the actual element order is significant. The comparison function is user-defined.


Parameter Description
array Required. Specifies an array.

Required. Use if defined function to compare values and to sort them.

The function must return -1, 0, or 1 for this method to work correctly. It should be written to accept two parameters to compare, and it should work something like this −

  • If a = b, return 0
  • If a > b, return 1
  • If a < b, return -1

Return Value

Returns TRUE on success or FALSE on failure.


Try out following example −

   function cmp_function($a, $b)
      if ($a == $b) return 0;
      return ($a > $b) ? -1 : 1;
   $fruits = array("d"=>"lemon", "a"=>"orange", "b"=>"banana" );
   uasort($fruits, "cmp_function");

This will produce the following result −

Array ( [a] => orange [d] => lemon [b] => banana )