In this tutorial, you shall learn how to sort an array of strings in PHP using sort() or rsort() functions, with example programs.

PHP – Sort an Array of Strings

To sort an array of strings in PHP, we can use sort() or rsort() array functions.

  • sort() can take an array of strings as argument, and sorts the elements in ascending order. Array of strings are sorted lexicographically (order of dictionary).
  • rsort() can take an array of strings as argument, and sorts the elements in descending order lexicographically.

Examples

1. Sort Array of Strings in Ascending Order

In the following example, we will take an array of strings, and sort the array in ascending order lexicographically using sort() function.

PHP Program

</>
Copy
<?php
$names = array("banana", "cherry", "apple", "mango");
printf("Original Array : %s <br>", implode(" ", $names));

sort($names);
printf("Sorted Array : %s", implode(" ", $names));
?>

Output