PHP Array Sorting

Elements in the array can be sorted in ascending or descending order by letter or number.

PHP - Array Sorting Functions

In this section, we will learn the following PHP array sorting functions:

  • sort() - Sorts the array in ascending order
  • rsort() - Sorts the array in descending order
  • asort() - Sorts associative arrays in ascending order by value
  • ksort() - Sorts associative arrays in ascending order by key
  • arsort() - Sorts associative arrays in descending order by value
  • krsort() - Sorts associative arrays in descending order by key

Ascending sort of the array - sort()

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

Example

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

Running Instances

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

Example

<?php
$numbers=array(3,5,1,22,11);
sort($numbers);
?>

Running Instances

Sort an array in descending order - rsort()

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

Example

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

Running Instances

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

Example

<?php
$numbers=array(3,5,1,22,11);
rsort($numbers);
?>

Running Instances

Sort an array in ascending order by value - asort()

The following example sorts an associative array in ascending order by value:

Example

<?php
$age=array("Bill"=>"63","Steve"=>"56","Elon"=>"47");
asort($age);
?>

Running Instances

Sort an array in ascending order by key - ksort()

The following example sorts an associative array in ascending order by key:

Example

<?php
$age=array("Bill"=>"63","Steve"=>"56","Elon"=>"47");
ksort($age);
?>

Running Instances

Sort an array in descending order by value - arsort()

The following example sorts an associative array in descending order by value:

Example

<?php
$age=array("Bill"=>"63","Steve"=>"56","Elon"=>"47");
arsort($age);
?>

Running Instances

Sort an array in descending order by key - krsort()

The following example sorts an associative array in descending order by key:

Example

<?php
$age=array("Bill"=>"63","Steve"=>"56","Elon"=>"47");
krsort($age);
?>

Running Instances

Complete PHP Array Reference Manual

For a complete reference manual of array functions, please visit our PHP Array Reference Manual.

This reference manual includes a brief description and usage examples for each function.