w3resource

PHP: asort() function

PHP: Sort an array and maintain index association

The asort() function is used to sorts an array. The function maintains index association.

This function is used mainly when sorting associative arrays where the actual element order is significant.

Version:

(PHP 4 and above)

Syntax:

asort(array_name, sort_type)

Parameters:

Name Description Required /
Optional
Type
array_name Specifies the name of the array to sort. Required Array
sort_type Sets the sorting behavior.
Possible type :
SORT_REGULAR - Compare items normally.
SORT_NUMERIC - Compare items numerically.
SORT_STRING - Compare items as strings.
SORT_LOCALE_STRING - compare items as strings, based on the current locale
Optional Integer

Return value:

TRUE on success or FALSE on failure.

Value Type: Boolean.

Example:

<?php
$subject = array('d' => 'Language',  'c' => 'Math',  'a' => 'Science', 'b'=> 'Geography');
asort($subject);
foreach ($subject as $key => $val)
{
echo "$key = $val <br />";
}
?>

Output:

b = Geography
d = Language
c = Math
a = Science 

View the example in the browser

Practice here online :

See also

PHP Function Reference

Previous: arsort
Next: compact



PHP: Tips of the Day

PHP: Extract numbers from a string

$str = 'In My Cart : 11 12 items';
preg_match_all('!\d+!', $str, $matches);
print_r($matches);