PHP asort() function

PHP asort() function

The asort() function in PHP is used to sort an array while maintaining the index association.

Syntax

asort ( array &$array [, int $sort_flags = SORT_REGULAR ] ) 

array(required)- This parameter represents the input array to sort.

sort_flags (optional)- This parameter is used to modify the behavior of the sort. The various possible values for sorting type flags are as follows:

  • SORT_REGULAR – It is used to compare items normally (don't change types)
  • SORT_NUMERIC – This flag is used to compare the items numerically.
  • SORT_STRING – It compares the given items as strings.
  • SORT_LOCALE_STRING – This flag compares the items as strings, based on the current locale.
  • SORT_NATURAL – It is used to compare items as strings using "natural ordering" like natsort().
  • SORT_FLAG_CASE – It can be combined (bitwise OR) with SORT_STRING or SORT_NATURAL to sort the given strings case-insensitively

Return

This function returns a Boolean value TRUE on success or FALSE on failure.

Example 1

"Reema", "Age"=>"23","Country"=>"India");
 //original array
 echo("Original array: \n");
 print_r($array);
 //sorting the array while maintaining the index association
 asort($array);
 //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 2

"Reema", "Age"=>23,"Country"=>"India");
 //original array
 echo("Original array: \n");
 print_r($array);
 //sorting the array while maintaining the index association
 asort($array );
 //printing the sorted array 
 echo("\nSorted array without second parameter: \n");
 print_r($array);
 //sorting array with second parameter as SORT_STRING 
 asort($array,SORT_STRING  );
 //printing the sorted array
 echo("\nSorted array with second parameter: \n");
 print_r($array);
 ?> 

Output

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

Example 3

"mango", 2 => "orange", 3 => "lichi", "apple");
 //sorting the array
 asort($fruits);
 echo("Sorted Array: \n");
 //printing the sorted values
 foreach ($fruits as $key => $val) {
     echo "$key = $val\n";
 }
 ?> 

Output

Sorted Array: 
4 = apple
3 = lichi
1 = mango
2 = orange