PHP asort

Summary: in this tutorial, you’ll learn how to use the PHP asort() function to sort an associative array and maintain the index association.

Introduction to the PHP asort() function

The asort() function sorts the elements of an associative array in ascending order. Unlike other sort functions, the asort() function maintains the index association.

The following shows the syntax of the asort() function:

asort(array &$array, int $flags = SORT_REGULAR): boolCode language: PHP (php)

The asort() function has two parameters:

  • $array is the input array.
  • $flags is one or more flags that change the sorting behavior.

The asort() function returns a boolean value, true on success or false on failure.

PHP asort() function example

The following example shows how to use the asort() function to sort an associative array:

<?php

$mountains = [
    'K2' => 8611,
    'Lhotse' => 8516,
    'Mount Everest' => 8848,
    'Kangchenjunga' => 8586,
];
asort($mountains);

print_r($mountains);Code language: PHP (php)

Output:

Array
(
    [Lhotse] => 8516
    [Kangchenjunga] => 8586
    [K2] => 8611
    [Mount Everest] => 8848
)    Code language: PHP (php)

How it works.

  • First, define an associative array representing the top mountains where each element has a key as the mountain name and value as the height.
  • Second, use the asort() function to sort the array.

PHP arsort() function

To sort an associative array in descending order and maintain the index association, you use the arsort() function:

arsort(array &$array, int $flags = SORT_REGULAR): boolCode language: PHP (php)

The following example uses the arsort() function to sort the $mountains array in descending order:

<?php

$mountains = [
    'K2' => 8611,
    'Lhotse' => 8516,
    'Mount Everest' => 8848,
    'Kangchenjunga' => 8586,
];
arsort($mountains);

print_r($mountains);Code language: PHP (php)

Output:

Array
(
    [Mount Everest] => 8848
    [K2] => 8611
    [Kangchenjunga] => 8586
    [Lhotse] => 8516       
)Code language: PHP (php)

Summary

  • Use the PHP asort() function to sort an associative array in ascending order and maintain index association.
  • To sort an associative array in descending order and maintain the index association, use the arsort() function.
Did you find this tutorial useful?