PHP Function Reference

PHP arsort() Function



The PHP arsort() function is used to sort an array in descending order, according to the value and maintaining key to value association. This is used mainly when sorting associative arrays where the actual element order is significant.

Syntax

arsort(array, flags)

Parameters

array Required. Specify the associative array to sort
flags Optional. Specify sorting type flags to modify the sorting behavior. Sorting type flags:
  • SORT_REGULAR - Default. Compare items normally.
  • SORT_NUMERIC - Compare items numerically.
  • SORT_STRING - Compare items as strings.
  • SORT_LOCALE_STRING - Compare items as strings, based on current locale.
  • SORT_NATURAL - Compare items as strings using natural ordering.
  • SORT_FLAG_CASE - Compare items as strings and case-insensitive. Can be combined (bitwise OR) with SORT_STRING or SORT_NATURAL.

Return Value

Returns true on success and false in failure.

Exceptions

NA.

Example:

In the example below, arsort() function is used to sort an associative array in descending order, according to the value.

<?php
$Arr = array("Marry"=>25, 
             "John"=>30, 
             "Jo"=>45, 
             "Kim"=>22, 
             "Adam"=>35);
                 
arsort($Arr);

print_r($Arr);
?>

The output of the above code will be:

Array
(
    [Jo] => 45
    [Adam] => 35
    [John] => 30
    [Marry] => 25
    [Kim] => 22
)

Example:

Consider one more example where this function is used to sort an associative array using case-insensitive natural ordering.

<?php
$Arr = array("Red"=>"Color1",
             "Green"=>"color2",
             "Blue"=>"Color3",
             "White"=>"Color20");

arsort($Arr, SORT_NATURAL | SORT_FLAG_CASE);

print_r($Arr);
?>

The output of the above code will be:

Array
(
    [White] => Color20
    [Blue] => Color3
    [Green] => color2
    [Red] => Color1
)

❮ PHP Array Reference