Sorting Associative Array in PHP

In this tutorial, you will learn about sorting associative array in PHP with the help of various examples. You can sort associative array in two ways, either by values or by keys.

PHP provides two built-in functions to sort associative arrays by values. They are:

  • asort() function
  • arsort() function

Similarly, PHP provides two built-in functions to sort associative array by keys. They are as:

  • ksort() function
  • krsort() function

Let’s discuss each function with various examples.

Sorting Associative Array in PHP by Values


1. asort() Function

The asort() function in PHP is used for sorting an associative array by its values in ascending order while maintaining the key-value associations. This means that the keys will remain associated with their respective values, even after sorting. The general syntax of asort() function in PHP is as:

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

In the above syntax of asort() function,

  • array represents the associative array that has to be sorted.
  • flags is an optional parameter that determines how the values will be compared. Their possible values include:
    • SORT_REGULAR (default): Compares values normally.
    • SORT_NUMERIC: Compares values numerically.
    • SORT_STRING: Compares values as strings.
    • SORT_LOCALE_STRING: Compares values as strings based on the current locale.
    • SORT_NATURAL: Compares values using “natural order”.
    • SORT_FLAG_CASE: Used with SORT_STRING or SORT_NATURAL to make the comparison case-insensitive.

This function returns boolean values, either true on successful operation or false on failure.

Example 1: Sorting an Associative Array by Values (Default Behavior)

<?php
$students = [
    "Alice" => 85,
    "Bob" => 92,
    "Charlie" => 78,
];
asort($students);
print_r($students);
?>
Output:
     Array
     (
       [Charlie] => 78
       [Alice] => 85
       [Bob] => 92
     )

In this example, the associative array is sorted by the numeric values (i.e. scores) in ascending order while maintaining the original keys.


Example 2: Sorting a String-Based Associative Array

<?php
$fruits = [
   "banana" => "yellow",
   "apple" => "green",
   "cherry" => "red",
   "orange" => "orange",
];
asort($fruits);
print_r($fruits);
?>
Output:
      Array
      (
        [apple] => green
        [orange] => orange
        [cherry] => red
        [banana] => yellow
      )

In this example, the string values (yellow, green, red) of keys in the associative array are sorted alphabetically in ascending order while preserving the original keys.

Example 4: Sorting with SORT_STRING Flag

<?php
$marks = [
   "Alice" => "85",
   "Bob" => "92",
   "Charlie" => "78",
];
asort($marks, SORT_STRING);
print_r($marks);
?>
Output:
      Array
     (
       [Charlie] => 78
       [Alice] => 85
       [Bob] => 92
     )

Mixed Data Types in Associative Array

Mixed data types in an associative array occur when they contain elements of different type, such as strings, integers, floats, booleans, etc. If you don’t explicitly handle the different data types, unexpected results can lead to sorting these arrays. Let’s take some examples on mixed data types.


Example 5: Sorting of Mixed Numeric and String Values

<?php
$data = [
   "key1" => 100,
   "key2" => "200",
   "key3" => "50",
   "key4" => 30,
];
asort($data);
print_r($data);
?>
Output:
      Array
     (
       [key4] => 30
       [key3] => 50
       [key1] => 100
       [key2] => 200
     )

In this example, we have compared numeric values such as 100 and 30 with string numeric values such as “200” and “50”. By default, PHP automatically treats numeric strings as numbers during comparisons when using asort() function with the default behavior. Therefore, the associative array is sorted numerically based on the values, regardless of whether the values are integers or numeric strings.

Example 6: Sorting with Booleans, Strings, and Numbers

<?php
$data = [
   "key1" => true,
   "key2" => false,
   "key3" => "apple",
   "key4" => 42,
];
asort($data);
print_r($data);
?>
Output:
      Array
      (
        [key2] => 
        [key1] => 1
        [key4] => 42
        [key3] => apple
      )

In this example, we have an associative array containing mixed types of values. We know that the value false is treated as 0, and true is treated as 1. The boolean values are sorted first because they are considered smaller than numbers. Then, numbers are sorted in ascending order. Strings are compared as greater than numeric values and are sorted last.

Example 7: Sorting with Null Values

<?php
$mixedData = [
   "key1" => null,
   "key2" => 10,
   "key3" => "hello",
   "key4" => 5,
];
asort($mixedData);
print_r($mixedData);
?>
Output:
      Array
     (
       [key1] => 
       [key4] => 5
       [key2] => 10
       [key3] => hello
     )

In this example, the null is treated as the smallest value during sorting. After that, numeric values are sorted, followed by the string.


Example 8: Case-Insensitive String Sorting

<?php
$data = [
   "key1" => "Banana",
   "key2" => "apple",
   "key3" => "cherry",
   "key4" => "Apple",
];
asort($data, SORT_STRING | SORT_FLAG_CASE);
print_r($data);
?>
Output:
      Array
     (
       [key2] => apple
       [key4] => Apple
       [key1] => Banana
       [key3] => cherry
     )

In this example, we have used the SORT_STRING | SORT_FLAG_CASE flag that ensures a case-insensitive comparison. PHP sorts alphabetically while ignoring case differences.

2. arsort() Function

The arsort() function in PHP works similar to asort() function. Only the difference is that this function sorts the associative array by its values in descending order while maintaining key-value associations.

Example 9: Sorting in Descending Order

<?php
$num = [
   "key1" => 20,
   "key2" => 5,
   "key3" => 10,
   "key4" => 1,
];
arsort($num);
print_r($num);
?>
Output:
      Array
     (
       [key1] => 20
       [key3] => 10
       [key2] => 5
       [key4] => 1
     )

Sorting Associative Array by Keys in PHP


You can sort associative arrays by keys using ksort() and krsort() functions. Let’s discuss one by one.

3. ksort() Function

The ksort() function in PHP sorts an associative array by its keys in ascending order, while preserving the association between keys and values. It sorts the keys in their natural order numerically for numbers and alphabetically for strings. The general syntax of this function is as:

ksort(array &$array, int $flags = SORT_REGULAR): bool

Example 10:

<?php
$data = [
   "A" => 20,
   "C" => 5,
   "B" => 10,
   "D" => 1,
];
arsort($data);
print_r($data);
?>
Output:
      Array
     (
        [A] => 20
        [B] => 10
        [C] => 5
        [D] => 1
     )

In this example, the keys of an associative array are sorted alphabetically in ascending order, while their associated values remain unchanged.

Example 11: Sorting Numeric Keys

<?php
$num = [
   3 => "Three",
   1 => "One",
   4 => "Four",
   2 => "Two",
];
ksort($num);
print_r($num);
?>
Output:
     Array
     (
       [1] => One
       [2] => Two
       [3] => Three
       [4] => Four
     )

In this example, the numeric keys of an associative array are sorted in ascending numerical order.

Example 12: Using SORT_STRING Flag for String Comparison

<?php
$data = [
   "10" => "Ten",
   "2" => "Two",
   "1" => "One",
   "12" => "Twelve",
];
ksort($data, SORT_STRING);
print_r($data);
?>
Output:
      Array
     (
       [1] => One
       [10] => Ten
       [12] => Twelve
       [2] => Two
     )

Example 13: Mixed Types of Keys

<?php
$data = [
   "20" => "Twenty",
    3 => "Three",
   "apple" => "Apple",
   "10" => "Ten",
];
ksort($data);
print_r($data);
?>
Output:
     Array
     (
       [3] => Three
       [10] => Ten
       [20] => Twenty
       [apple] => Apple
     )

In this example, we have a mixed data types of keys in the associative array. PHP sort numeric keys first in ascending order and then sort string keys alphabetically after numeric keys.

4. krsort() Function

The krsort() function in PHP sorts an associative array by its keys in descending order while maintaining the key-value relationships.

Example 14:

<?php
$name = [
   "John" => 20,
   "Bob" => 5,
   "Saanvi" => 10,
];
krsort($name);
print_r($name);
?>
Output:
     Array
     (
       [Saanvi] => 10
       [John] => 20
       [Bob] => 5
     )

Sorting Functions Overview


Here, we have listed all four built-in functions provided by PHP for sorting associative array based on its keys and values.

FunctionSort ByOrderMaintains Key-Value Pair
asort()ValueAscendingYes
arsort()ValueDescendingYes
ksort()KeyAscendingYes
krsort()KeyDescendingYes