PHP uasort() Function

PHP uasort() Function

The uasort() function in PHP sorts an array with a user-defined comparison function and maintains the index association.

Syntax

uasort ( array &$array , callable $value_compare_func )

Parameter

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

"Reema",2=>"Varun",1=>"Joe",4=>"Ron",3=>"Jai");
 //original array
 echo("Original array: \n");
 print_r($array);
 //Sorts the array with a user-defined comparison function while maintaining the index
 uasort($array,"strcasecmp");
 //printing the sorted array
 echo("\nSorted array: \n"); 
 print_r($array);
 ?> 

Output

Original array: 
 Array
 (
     [5] => Reema
     [2] => Varun
     [1] => Joe
     [4] => Ron
     [3] => Jai 
 )
 Sorted array: 
 Array
 (
     [3] => Jai
     [1] => Joe
     [5] => Reema
     [4] => Ron
     [2] => Varun
 ) 

Example 2

"Reema", "Age"=>23,"Country"=>"India");
 //original array
 echo("Original array: \n");
 print_r($array);
 //Sorts an array with a user-defined comparison function while maintaining the index association
 uasort($array,"strcasecmp" );
 //printing the sorted array
 echo("\nSorted array: \n"); 
 print_r($array);
 ?> 

Output

Original array: 
 Array
 (
     [Name] => Reema
     [Age] => 23
     [Country] => India
 )
 Sorted array: 
 Array 
 (
     [Age] => 23
     [Country] => India
     [Name] => Reema
 ) 

Example 3

$b)? 1: 0; 
 } 
 // initializing the Input Array 1 
 $array = array(05=>"Reema", 10=>"raj", 30=>"Atul"); 
 echo("Original Array: \n");
 print_r($array);
 // Sorting the array with "my_function" comparison function while maintaining the index
 uasort ($array,"my_function");
 echo("\nSorted Array: \n"); 
 print_r($array);
 ?> 

Output

Original Array: 
 Array
 (
     [5] => Reema
     [10] => raj
     [30] => Atul
 )
 Sorted Array:  
 Array
 (
     [30] => Atul
     [5] => Reema
     [10] => raj
 )