Categories
PHP

Sorting Associative Arrays

It’s often desirable to keep the key/value associations when sorting associative arrays. To maintain the key/value association the asort( ) and arsort( ) functions are used. Rather than sort on element values, the ksort( ) and krsort( ) functions rearrange elements in an array by sorting on the keys or the indexes.

When you try to use sort() or rsort() functions with an associative array, it works but the keys are then all lost. To keep key-value association intact, you must use one of the following sorting functions:

  1. asort() Sort associative arrays by values in ascending order
  2. arsort() Sort associative arrays by values in descending order
    Sorting associative arrays alphabetically
  3. ksort() Sort arrays by keys in ascending order
  4. krsort() Sort arrays by keys in descending order

These functions always return TRUE. These functions are useful mainly for associative arrays and accept two parameters:

  1. array as input
  2. Sorting flags (optional) to modify the behavior of the sort.
<?php
/*Sorting Associative Arrays (Syntax)
ksort (array &$array, int $flags = SORT_REGULAR): bool
krsort(array &$array, int $flags = SORT_REGULAR): bool

asort (array &$array, int $flags = SORT_REGULAR): bool
arsort(array &$array, int $flags = SORT_REGULAR): bool
*/

asort Sort associative arrays by values in ascending order

<?php
  $a = ['two' => 'II','four' => 'IV', 'three' => 'III', 'one' => 'I'];
  asort($a);
  print_r($a);

/* Prints
Array
(
    [one] => I
    [two] => II
    [three] => III
    [four] => IV
)
*/

Like sort( ) this function rearranges the elements in the subject array from lowest to highest. The following example shows a simple array sorted by asort( ):

<?php
 $map =  array("o"=>"kk", "e"=>"zz", "z"=>"hh", "a"=>"rr");
 asort($map);
 print_r($map);

The print_r( ) function outputs the structure of the sorted array:

Array ( [z] => hh
        [o] => kk
        [a] => rr
        [e] => zz )

When assort( ) and arsort( ) are used on nonassociative arrays, the order of the elements is arranged in sorted order, but the indexes that access the elements don’t change. This might seem a bit weird; effectively the indexes are treated as association keys in the resulting array. The following example shows what is happening:

<?php
 $numbers = array(24, 19, 3, 16, 56, 8, 171);
 asort($numbers);
 print_r($numbers);

This outputs:

Array ( [2] => 3
        [5] => 8
        [3] => 16
        [1] => 19
        [0] => 24
        [4] => 56
        [6] => 171 )

arsort Sort associative arrays by values in descending order

<?php
  $a = ['two' => 'II','four' => 'IV', 'three' => 'III', 'one' => 'I'];
  arsort($a);
  print_r($a);

/* Prints
Array
(
    [four] => IV
    [three] => III
    [two] => II
    [one] => I
)
*/

Like rsort( ) this function rearranges the elements in the subject array from highest to lowest. The following example shows a simple array sorted by arsort( ):

<?php
 $map =  array("o"=>"kk", "e"=>"zz", "z"=>"hh", "a"=>"rr");
 arsort($map);
 print_r($map);
 
 /* Prints
 Array
(
    [e] => zz
    [a] => rr
    [o] => kk
    [z] => hh
)
 */

Sorting Associative Arrays Alphabetically

<?php
 $a = ['tf'=>24, 'nt'=>19, 'te'=>3, 'sn'=>16,
       'fs'=>56, 'et'=>8, 'oso'=>171];
 asort($a);
 print_r($a);

The output of the example shows the result:

//Numerically sorted
Array
(
    [te] => 3
    [et] => 8
    [sn] => 16
    [nt] => 19
    [tf] => 24
    [fs] => 56
    [oso] => 171
)

By default, PHP sorts strings in alphabetical order and numeric values in numeric order. An optional parameter, sorting flag, can be passed to force the string or numeric sorting behavior. In the following example, the PHP constant SORT_STRING sorts the numbers as if they were strings:

<?php
 $a = ['tf'=>24, 'nt'=>19, 'te'=>3, 'sn'=>16,
       'fs'=>56, 'et'=>8, 'oso'=>171];
 asort($a, SORT_STRING);
 print_r($a);

The output of the example shows the result:

//Alphabetically sorted
Array
(
    [sn] => 16
    [oso] => 171
    [nt] => 19
    [tf] => 24
    [te] => 3
    [fs] => 56
    [et] => 8
)

ksort Sort arrays by keys in ascending order

ksort( ) sorts the elements in an array from lowest key to highest key (in alphabetic order). The following example demonstrates the ksort( ) function.

<?php
  $a = ['two' => 'II','four' => 'IV', 'three' => 'III', 'one' => 'I'];
  ksort($a);
  print_r($a);

/* Prints
Array
(
    [four] => IV
    [one] => I
    [three] => III
    [two] => II
)
*/

ksort() function, another example:

<?php
 $map =  array("o"=>"kk", "e"=>"zz", "z"=>"hh", "a"=>"rr");
 ksort($map);
 print_r($map);
 
 /* Prints
Array
(
    [a] => rr
    [e] => zz
    [o] => kk
    [z] => hh
)
 */

krsort Sort arrays by keys in descending order

krsort( ) sorts the elements in the subject array from highest key to lowest key (in reverse alphabetic order). The following example demonstrates the krsort( ) function:

<?php
  $a = ['two' => 'II','four' => 'IV', 'three' => 'III', 'one' => 'I'];
  krsort($a);
  print_r($a);

/* Prints
Array
(
    [two] => II
    [three] => III
    [one] => I
    [four] => IV
)

krsort() function, another example:

<?php
 $map =  array("o"=>"kk", "e"=>"zz", "z"=>"hh", "a"=>"rr");
 krsort($map);
 print_r($map);
 
 /* Prints
Array
(
    [z] => hh
    [o] => kk
    [e] => zz
    [a] => rr
)
 */

More Posts on PHP Sorting Arrays:

  1. Sort arrays in ascending or descending order
  2. Sort associative arrays
  3. Sort with user-defined criteria/function
  4. Sort multiple or multidimensional arrays
  5. Sort nested arrays
  6. Natural alphanumeric sort order
  7. Shuffle arrays grab random elements
  8. Working with arrays