PHP Array Sorting


Elements in an array can be sorted in ascending or descending order, alphabetically or numerically.


PHP - Array Sorting Functions

In this chapter, we will introduce the following PHP array sorting functions one by one:

  • sort() - Sort arrays in ascending order
  • rsort() - Sort arrays in descending order
  • asort() - Sort associative arrays in ascending order, according to the value
  • ksort() - Sort associative arrays in ascending order, according to the key
  • arsort() - Sort associative arrays in descending order, according to the value
  • krsort() - Sort associative arrays in descending order, according to the key

sort() - Sort arrays in ascending order

The following example sorts the elements of the $cars array in alphabetical ascending order:

Example

<?php
$cars=array("Volvo","BMW","Toyota");
sort($cars);
?>

Run example »

The following example sorts the elements of the $numbers array in numerical ascending order:

Example

<?php
$numbers=array(4,6,2,22,11);
sort($numbers);
?>

Run example »


rsort() - Sort arrays in descending order

The following example sorts the elements of the $cars array in alphabetical descending order:

Example

<?php
$cars=array("Volvo","BMW","Toyota");
rsort($cars);
?>

Run example »

The following example sorts the elements of the $numbers array in numerical descending order:

Example

<?php
$numbers=array(4,6,2,22,11);
rsort($numbers);
?>

Run example »


asort() - Sort associative arrays in ascending order, according to the value

The following example sorts an associative array in ascending order, according to the value:

Example

<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
asort($age);
?>

Run example »


ksort() - Sort associative arrays in ascending order, according to the key

The following example sorts an associative array in ascending order, according to the key:

Example

<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
ksort($age);
?>

Run example »


arsort() - Sort associative arrays in descending order, according to the value

The following example sorts an associative array in descending order, according to the value:

Example

<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
arsort($age);
?>

Run example »


krsort() - Sort associative arrays in descending order, according to the key

The following example sorts an associative array in descending order, according to the key:

Example

<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
krsort($age);
?>

Run example »


Complete PHP Array Reference

For a complete reference of all array functions, visit ourPHP Array Reference。

This reference manual provides a brief description and application examples for each function!

Other Extensions