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
";
}
?>
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
";
}
echo "<br>";
$fruits2 = array("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple");
ksort($fruits2);
foreach ($fruits2 as $key => $val) {
    echo "$key = $val
";
}
?>
krsort()

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

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendPHPphp-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

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.