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
</>
Copy
<?php
$nums = array(5, 2, 9, 1);
printf("Original Array : %s <br>", implode(" ", $nums));
sort($nums);
printf("Sorted Array : %s", implode(" ", $nums));
?>
Output
