PHP asort() Function (original) (raw)

Skip to content

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:

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)

Try it

Output:

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

How it works.

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)

Try it

Output:

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

Summary #

Did you find this tutorial useful?