To sort an array in PHP, you can use the sort()
function for ascending order and rsort()
function for descending order.
In this example,
$numbers
with values 5, 2, 8, 1, 6.sort()
function on the array to sort it in ascending order.sort()
function sorts the array elements in ascending order.$numbers
using print_r()
.<?php
$numbers = array(5, 2, 8, 1, 6);
sort($numbers);
echo "Sorted array in ascending order: ";
print_r($numbers);
echo "\n";
?>
Sorted array in ascending order: Array ( [0] => 1 [1] => 2 [2] => 5 [3] => 6 [4] => 8 )
In this example,
$numbers
with values 5, 2, 8, 1, 6.rsort()
function on the array to sort it in descending order.rsort()
function sorts the array elements in descending order.$numbers
using print_r()
.<?php
$numbers = array(5, 2, 8, 1, 6);
rsort($numbers);
echo "Sorted array in descending order: ";
print_r($numbers);
echo "\n";
?>
Sorted array in descending order: Array ( [0] => 8 [1] => 6 [2] => 5 [3] => 2 [4] => 1 )
In this tutorial, we learned How to Sort an Array in PHP language with well detailed examples.