Array Functions

PHP asort() Function

Topic: PHP Array ReferencePrev|Next

Description

The asort() function sorts an associative array in ascending order, according to the value.

The keys are preserved, i.e. the key-to-value mapping will remain unchanged by the sort operation.

The following table summarizes the technical details of this function.

Return Value: Returns TRUE on success or FALSE on failure.
Version: PHP 4+

Syntax

The basic syntax of the asort() function is given with:

asort(array, sort_flags);

The following example shows the asort() function in action.

<?php
// Sample array
$alphabets = array("b"=>"ball", "d"=>"dog", "a"=>"apple", "c"=>"cat");

// Sorting alphabets array
asort($alphabets);
print_r($alphabets);
?>

Tip: The asort() and arsort() functions mainly used for sorting associative arrays by value, whereas ksort() and krsort() functions used for sorting associative arrays by key.


Parameters

The asort() function accepts the following parameters.

Parameter Description
array Required. Specifies the array to sort.
sort_flags

Optional. Specifies how array items should be compared. Possible values are:

  • SORT_REGULAR – Compare items normally (don't change types). Default value.
  • SORT_NUMERIC – Compare items numerically.
  • SORT_STRING – Compare items as strings.
  • SORT_LOCALE_STRING – Compare items as strings, based on the current locale.
  • SORT_NATURAL – Compare items as strings using natural ordering.
  • SORT_FLAG_CASE – Can be combined (bitwise OR) with SORT_STRING or SORT_NATURAL to sort strings case-insensitively.

More Examples

Here're some more examples showing how asort() function actually works:

The following example sorts an associative array having numeric values in ascending order:

<?php
// Sample array
$persons = array("Harry"=>18, "Clark"=>32, "Peter"=>20, "John"=>24);

// Sorting persons array
asort($persons);
print_r($persons);
?>
Bootstrap UI Design Templates Property Marvels - A Leading Real Estate Portal for Premium Properties