PHP asort() Function

Definition

The asort() function takes an array and sorts it by its values while preserving the keys.

Note

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

Syntax

PHP asort() 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

Example 1

Sort an associative array in ascending order, according to the value:


<?php//from w w w .j a  v  a 2  s. c  om
    $age=array("PHP"=>"5","Java"=>"7","java2s.com"=>"9");
    asort($age);
    print_r($age);
?>

The code above generates the following result.

Example 2

asort() works by directly changing the value you pass in. The return value is either true or false, depending on whether the sorting was successful.


<?PHP/*w  ww. j av a  2s  .com*/
$capitalcities['Key1'] = 'Z';
$capitalcities['Key2'] = 'X';
$capitalcities['Key3'] = 'Y';
asort($capitalcities);
print_r($capitalcities);
?>

The code above generates the following result.





















Home »
  PHP Tutorial »
    Function reference »




PHP Array Functions
PHP Calendar Functions
PHP Class Functions
PHP Data Type Functions
PHP Date Functions
PHP File Functions
PHP Image Functions
PHP Math Functions
PHP MySQLi Functions
PHP SimpleXML Functions
PHP String Functions
PHP XML Functions
PHP Zip Functions