PHP asort() Function
In this chapter you will learn:
- Definition for PHP asort() Function
- Note for PHP asort() Function
- Syntax for PHP asort() Function
- Parameter for PHP asort() Function
- Example - Sort an associative array in ascending order, according to the value:
- Example - asort() works by directly changing the value you pass in
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
Parameter | Is Required | Description |
---|---|---|
array | Required. | Array to sort |
sortingtype | Optional. | How to compare the array elements/items. |
Possible values for sortingtype:
Value | Description |
---|---|
0 = SORT_REGULAR | Default. Compare items normally (don't change types) |
1 = SORT_NUMERIC | Compare items numerically |
2 = SORT_STRING | Compare items as strings |
3 = SORT_LOCALE_STRING | Compare items as strings, based on current locale |
4 = SORT_NATURAL | Compare items as strings using natural ordering |
5 = SORT_FLAG_CASE | can 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 j a v a2s.co m*/
$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/*j a v a2 s. c o m*/
$capitalcities['Key1'] = 'Z';
$capitalcities['Key2'] = 'X';
$capitalcities['Key3'] = 'Y';
asort($capitalcities);
print_r($capitalcities);
?>
The code above generates the following result.
Next chapter...
What you will learn in the next chapter:
- Definition for PHP compact() Function
- Syntax for PHP compact() Function
- Parameter for PHP compact() Function
- Example - Create an array with compact
- Example - Using a string that does not match a variable, and an array of variable names
Home » PHP Tutorial » PHP Array Functions