Computer >> Computer tutorials >  >> Programming >> PHP

asort() function in PHP


The asort() function sorts an associative array in ascending array and maintain index association.

Syntax

asort(arr, compare)

Parameters

  • arr − The specified array.

  • compare − Specifies how to compare the array elements/items. Possible values−

    • SORT_STRING − Compare items as strings

    • SORT_REGULAR − Compare items without changing types

    • SORT_NUMERIC − Compare items numerically

    • SORT_LOCALE_STRING − Compare items as strings, based on current local.

    • SORT_NATURAL − Compare items as strings using natural ordering

Return

The asort() function returns TRUE on success and FALSE on failure.

Example

The following is an example −

<?php
$a = array(
   "0" => "India",
   "1" => "Australia",
   "2" => "England",
   "3" => "Bangladesh",
   "4" => "Zimbabwe",
);
asort($a);
foreach ($a as $key => $val) {
   echo "[$key] = $val";
   echo"\n";
}
?>

Output

[1] = Australia
[3] = Bangladesh
[2] = England
[0] = India
[4] = Zimbabwe