PHP Array Sorting
Array elements can be sorted in ascending or descending order by alphabetical or numerical order.
PHP - Array Sorting Functions
In this chapter, we will introduce the following PHP array sorting functions:
sort()
- Sorts an array in ascending orderrsort()
- Sorts an array in descending orderasort()
- Sorts an array by value in ascending order, maintaining key associationsksort()
- Sorts an array by key in ascending order, maintaining key associationsarsort()
- Sorts an array by value in descending order, maintaining key associationskrsort()
- Sorts an array by key in descending order, maintaining key associations
sort()
- Sorts an Array in Ascending Order
The following example sorts the $cars
array elements in alphabetical ascending order:
Example
<?php
$cars = array("Volvo", "BMW", "Toyota");
sort($cars);
?>
The following example sorts the $numbers
array elements in numerical ascending order:
Example
<?php
$numbers = array(4, 6, 2, 22, 11);
sort($numbers);
?>
rsort()
- Sorts an Array in Descending Order
The following example sorts the $cars
array elements in alphabetical descending order:
Example
<?php
$cars = array("Volvo", "BMW", "Toyota");
rsort($cars);
?>
The following example sorts the $numbers
array elements in numerical descending order:
Example
<?php
$numbers = array(4, 6, 2, 22, 11);
rsort($numbers);
?>
asort()
- Sorts an Array by Value in Ascending Order
The following example sorts the associative array by value in ascending order:
Example
<?php
$age = array("Peter" => "35", "Ben" => "37", "Joe" => "43");
asort($age);
?>
ksort()
- Sorts an Array by Key in Ascending Order
The following example sorts the associative array by key in ascending order:
Example
<?php
$age = array("Peter" => "35", "Ben" => "37", "Joe" => "43");
ksort($age);
?>
arsort()
- Sorts an Array by Value in Descending Order
The following example sorts the associative array by value in descending order:
Example
<?php
$age = array("Peter" => "35", "Ben" => "37", "Joe" => "43");
arsort($age);
?>
krsort()
- Sorts an Array by Key in Descending Order
The following example sorts the associative array by key in descending order:
Example
<?php
$age = array("Peter" => "35", "Ben" => "37", "Joe" => "43");
krsort($age);
?>
Complete PHP Array Reference Manual
To view the complete reference manual for all array functions, please visit our PHP Array Reference Manual.
This reference manual provides a brief description and application examples for each function!