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

PHP – Sort an Array

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

  • sort() takes an array as argument, and sorts the elements in ascending order.
  • rsort() takes an array as argument, and sorts the elements in descending order.

Examples

1. Sort Array in Ascending Order

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

PHP Program

<?php
$nums = array(5, 2, 9, 1);
printf("Original Array : %s <br>", implode(" ", $nums));

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

Output

2. Sort Array in Descending Order

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

PHP Program

<?php
$nums = array(5, 2, 9, 1);
printf("Original Array : %s <br>", implode(" ", $nums));

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

Output

Conclusion

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