In this tutorial we will learn How to Sort array in alphabetical order with PHP, We can use PHP sort() function or rsort() function to sort any php array in alphabetical order, both ascending and descending.
Table of Contents
PHP sort() function
PHP sort() function sorts indexed or numeric array in ascending order.
The sort() function takes two things as a parameter, an array and the value to define the sorttype.
The sort() function returns 1 after sorting the array.
PHP rsort() function
PHP rsort() function sorts an indexed or numerical array in descending order.
The rsort() function also takes two parameters, array and sorttype value.
rsort() function is supported in PHP4+ versions.
Sorting array in alphabetical ascending order
<?php
$array=array("Red","Blue","Yellow","Pink","Orange");
sort($array);
print_r($array);
?>
Sorting array in alphabetical descending order
<?php
$array=array("Red","Blue","Yellow","Pink","Orange");
rsort($array);
print_r($array);
?>