Latest web development tutorials

PHP array sort

Array elements can be ascending or descending alphabetical or numerical order.


PHP - array sort function

In this chapter, we will introduce one by one the following PHP array sort function:

  • sort () - The array must be in ascending order
  • rsort () - array in descending order
  • asort () - based on the value associated with the array, the array in ascending order
  • ksort () - according to a key associative array, the array in ascending order
  • arsort () - based on the value associated with the array, the array in descending order
  • krsort () - according to a key associative array, the array in descending order

sort () - The array must be in ascending order

The following examples will be $ cars array element according to the ascending alphabetical order:

Examples

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

Running instance »

The following examples will be $ numbers array elements in ascending order according to the numbers:

Examples

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

Running instance »


rsort () - array in descending order

The following examples will be $ cars array elements in descending order according to the letters:

Examples

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

Running instance »

The following examples will be $ numbers array elements in descending order according to the numbers:

Examples

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

Running instance »


asort () - based on the value of the array, the array in ascending order

The following examples are based on the value of the array, associative array in ascending order:

Examples

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

Running instance »


ksort () - according to a key array, the array in ascending order

The following examples are based on the key array, associative array in ascending order:

Examples

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

Running instance »


arsort () - based on the value of the array, the array in descending order

The following examples are based on the value of the array, associative array in descending order:

Examples

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

Running instance »


krsort () - according to a key array, the array in descending order

The following examples are based on the key array of associative arrays in descending order:

Examples

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

Running instance »


Complete PHP Array Reference

For a complete reference manual for all array functions, visit our PHP Array Reference Manual .

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