THE WORLD'S LARGEST WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

PHP 5 Sorting Arrays


The elements in the array can be sorted in descending or ascending alphabetical or numerical order.


PHP-array sort function

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

  • sort ()-Sort the array in ascending order
  • rsort ()-Sort the array in descending order
  • asort ()-sort the array in ascending order based on the value of the associative array
  • ksort ()-Sort the array in ascending order based on the keys of the associative array
  • arsort ()-sort the array in descending order based on the value of the associative array
  • krsort ()-Sort the array in descending order based on the keys of the associative array

sort ()-Sort the array in ascending order

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

Example

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

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

Example

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



rsort ()-Sort the array in descending order

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

Example

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

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

Example

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



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

The following example sorts the associative array in ascending order based on the value of the array:

Example

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



ksort ()-Sort the array in ascending order based on the keys of the array

The following example sorts the associative array in ascending order based on the keys of the array:

Example

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



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

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

Example

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



krsort ()-Sort the array in descending order based on the keys of the array

The following example sorts the associative array in descending order according to the keys of the array:

Examples

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