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

ADVERTISEMENT

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

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

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

Output

2. Sort Array of Strings in Descending Order

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

PHP Program

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

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

Output

Conclusion

In this PHP Tutorial, we learned how to sort an array of strings in ascending or descending order using sort() or rsort() function with examples.