PHP usort() Function
PHP usort() Function
The usort() function in PHP sorts array by values using a user-defined comparison function.
Syntax
usort ( array &$array , callable $value_compare_func )
array(required)- This parameter represents the input array.
value_compare_func(required)- This parameter represents a string that describe a callable comparison function. The comparison function must return an integer <, =, or > than 0 if the first argument is <, =, or > than the second argument.
Return
This function returns a Boolean value TRUE on success or FALSE on failure.
Example 1
"green", "b" => "brown", "i" => "indigo", "red"); echo("Input Array: \n"); print_r($array); //sorting the array by values using a "strcasecmp" comparison function usort($array, "strcasecmp"); echo("Sorted Array: \n"); print_r($array); ?>
Output
Input Array: Array ( [g] => green [b] => brown [i] => indigo [0] => red ) Sorted Array: Array ( [0] => brown [1] => green [2] => indigo [3] => red )
Example 2
$b)?1:-1; } $array1=array("1"=>"red","2"=>"green","3"=>"blue"); echo("Original Array: \n"); print_r($array1); // comparing the keys and values with additional index check usort ($array1,"myfunction"); echo("\nSorted Array: \n"); print_r($array1); ?>
Output
Original Array: Array ( [1] => red [2] => green [3] => blue ) Sorted Array: Array ( [0] => blue [1] => green [2] => red )
Example 3
$b)? 1: 0; } // initializing the Input Array 1 $array1 = array(05=>"Reema", 10=>"raj", 30=>"Atul"); echo("Original Array: \n"); print_r($array1); // comparing the keys and values with additional index check usort ($array1,"my_function"); echo("\nSorted Array: \n"); print_r($array1); ?>
Output
Original Array: Array ( [5] => Reema [10] => raj [30] => Atul ) Sorted Array: Array ( [0] => Atul [1] => Reema [2] => raj )