PHP Tutorial - PHP arsort() Function






Definition

The arsort() function reverse sorts array by its values while preserving the keys.

Note

The arsort() function is used to sort associative array. It is the associative array version of rsort().

Syntax

PHP arsort() Function has the following syntax.

bool arsort ( array &arr [, int options] )

Parameter

ParameterIs RequiredDescription
arrayRequired.Array to sort
sortingtypeOptional.How to compare the array elements/items.

Possible values for sortingtype:

ValueDescription
0 = SORT_REGULARDefault. Compare items normally (don't change types)
1 = SORT_NUMERICCompare items numerically
2 = SORT_STRINGCompare items as strings
3 = SORT_LOCALE_STRINGCompare items as strings, based on current locale
4 = SORT_NATURALCompare items as strings using natural ordering
5 = SORT_FLAG_CASEcan be combined bitwise OR with SORT_STRING or SORT_NATURAL to sort strings case-insensitively

This is the opposite of the asort().





Example 1

Reverse sorts array by its values


<?PHP
$capitalcities['Key1'] = 'Z';
$capitalcities['Key2'] = 'X';
$capitalcities['Key3'] = 'Y';

arsort($capitalcities);
print_r($capitalcities);
?>

The ksort() can take custom function for determining the sequence.

The code above generates the following result.





Example 2

Reverse sorts array by its values and output its keys and values


<?php

$fruits = array("A", "B", "C", "java2s.com");
arsort($fruits);
foreach ($fruits as $key => $val) {
    echo "fruits[" . $key . "] = " . $val . "\n";
}

?>

The code above generates the following result.

Example 3

arsort() example using case-insensitive natural ordering


<?php// w w w.  ja  v a  2s  .c  o  m

$fruits = array(
    "PHP1", "php2", "PHP3", "php20"
);
arsort($fruits, SORT_NATURAL | SORT_FLAG_CASE);
foreach ($fruits as $key => $val) {
    echo "fruits[" . $key . "] = " . $val . "\n";
}

?>

The code above generates the following result.