Backend Development 3 min read

Sorting Arrays in PHP: Using sort(), rsort(), asort(), arsort(), ksort() and krsort()

This tutorial explains how to sort both indexed and associative PHP arrays using built‑in functions such as sort, rsort, asort, arsort, ksort, and krsort, providing code examples and describing the resulting order for each method.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Sorting Arrays in PHP: Using sort(), rsort(), asort(), arsort(), ksort() and krsort()

PHP arrays are commonly used, and sorting them helps data management. This article demonstrates how to sort arrays using built‑in PHP functions.

1. Sorting indexed arrays by values

<?php
$arr1 = array(3,1,5,2,0);
sort($arr1);
print_r($arr1);
echo "<br>";
$arr2 = array(3,1,5,2,0);
rsort($arr2);
print_r($arr2);
?>

sort() arranges the array in ascending order, while rsort() arranges it in descending order.

2. Sorting associative arrays by values

<?php
$fruits1 = array("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple");
arsort($fruits1);
foreach ($fruits1 as $key => $val) {
    echo "$key = $val;";
}
echo "<br>";
$fruits2 = array("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple");
asort($fruits2);
foreach ($fruits2 as $key => $val) {
    echo "$key = $val\n";
}
?>

arsort() sorts an associative array by its values in descending order, whereas asort() sorts them in ascending order.

3. Sorting associative arrays by keys

<?php
$fruits1 = array("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple");
krsort($fruits1);
foreach ($fruits1 as $key => $val) {
    echo "$key = $val\n";
}
echo "<br>";
$fruits2 = array("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple");
ksort($fruits2);
foreach ($fruits2 as $key => $val) {
    echo "$key = $val\n";
}
?>

krsort() sorts an associative array by its keys in descending order, while ksort() sorts them in ascending order.

Programmingphp-functionsarray-sorting
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.