PHP Array Sort: sort(), asort(), ksort() Explained with Examples

Sorting arrays is a common task in PHP. You may want to sort numbers, names, prices, or even associative arrays by key or value.

PHP provides multiple sorting functions like sort(), asort(), and ksort(). Each one works slightly differently based on what you want to sort and whether you want to preserve keys.

This tutorial is a focused supporting guide for the main PHP arrays tutorial. Here, we will clearly explain the differences between sorting functions, when to use each one, and common mistakes.

Quick Answer

Use different functions based on your need:

  • sort() – Sort values and reindex keys
  • asort() – Sort values and keep keys
  • ksort() – Sort array by keys
<?php
$numbers = [30, 10, 20];

sort($numbers);

print_r($numbers);
?>

Output:

Array
(
    [0] => 10
    [1] => 20
    [2] => 30
)

The values are sorted in ascending order. The keys are reset.

PHP Array Sorting Functions

PHP has separate sorting functions for different needs. The main difference is whether the function sorts by value or key, and whether it preserves the original keys.

Function Sorts by Key behavior Use case
sort() Value Resets numeric keys Simple indexed arrays
rsort() Value Resets numeric keys Descending indexed arrays
asort() Value Preserves keys Associative arrays sorted by value
arsort() Value Preserves keys Associative arrays sorted by value descending
ksort() Key Preserves keys Associative arrays sorted by key
krsort() Key Preserves keys Associative arrays sorted by key descending

The easiest way to choose is simple. Use sort() for normal lists. Use asort() when the keys are important. Use ksort() when you want to order the array by key.

Sort an Indexed Array with sort()

The sort() function sorts array values in ascending order. It also resets the numeric keys.

<?php
$fruits = ["Orange", "Apple", "Banana"];

sort($fruits);

print_r($fruits);
?>

Output:

Array
(
    [0] => Apple
    [1] => Banana
    [2] => Orange
)

This is useful when the array is just a simple list and the original numeric keys do not matter.

Sort in Descending Order with rsort()

The rsort() function sorts an indexed array in descending order. Like sort(), it also resets the numeric keys.

<?php
$scores = [80, 95, 70, 88];

rsort($scores);

print_r($scores);
?>

Output:

Array
(
    [0] => 95
    [1] => 88
    [2] => 80
    [3] => 70
)

Use rsort() when you want the highest value first, such as top scores, highest prices, or latest priority values.

Preserve Keys While Sorting Values with asort()

The asort() function sorts an array by value and keeps the original keys.

This is useful for associative arrays where the key has meaning.

<?php
$productPrices = [
    "Keyboard" => 1200,
    "Mouse" => 600,
    "Monitor" => 9500
];

asort($productPrices);

print_r($productPrices);
?>

Output:

Array
(
    [Mouse] => 600
    [Keyboard] => 1200
    [Monitor] => 9500
)

The products are sorted by price. The product names are still preserved as keys.

Sort Associative Array Values in Descending Order with arsort()

The arsort() function sorts an associative array by value in descending order. It also preserves the keys.

<?php
$productPrices = [
    "Keyboard" => 1200,
    "Mouse" => 600,
    "Monitor" => 9500
];

arsort($productPrices);

print_r($productPrices);
?>

Output:

Array
(
    [Monitor] => 9500
    [Keyboard] => 1200
    [Mouse] => 600
)

Use arsort() when the highest value should come first and the array keys should remain connected to their values.

Sort by Keys with ksort()

The ksort() function sorts an associative array by key in ascending order.

<?php
$userRoles = [
    "editor" => "Edit posts",
    "admin" => "Manage site",
    "author" => "Write posts"
];

ksort($userRoles);

print_r($userRoles);
?>

Output:

Array
(
    [admin] => Manage site
    [author] => Write posts
    [editor] => Edit posts
)

This is useful when you want configuration arrays, labels, or grouped values to appear in key order.

Sort Keys in Descending Order with krsort()

The krsort() function sorts an associative array by key in descending order.

<?php
$userRoles = [
    "editor" => "Edit posts",
    "admin" => "Manage site",
    "author" => "Write posts"
];

krsort($userRoles);

print_r($userRoles);
?>

Output:

Array
(
    [editor] => Edit posts
    [author] => Write posts
    [admin] => Manage site
)

Natural Sorting with natsort()

Normal sorting can feel wrong when strings contain numbers. For example, file10 may come before file2.

Use natsort() when you want values to be sorted in a natural human-readable order.

<?php
$files = ["file10.txt", "file2.txt", "file1.txt"];

natsort($files);

print_r($files);
?>

Output:

Array
(
    [2] => file1.txt
    [1] => file2.txt
    [0] => file10.txt
)

natsort() keeps the original keys. If you need fresh numeric keys after sorting, use array_values().

Reindex Array After Sorting

Some sorting functions preserve keys. This is useful in many cases. But sometimes, you may want the sorted array to have fresh numeric keys starting from 0.

Use array_values() after sorting to reindex the array.

<?php
$files = ["file10.txt", "file2.txt", "file1.txt"];

natsort($files);

$files = array_values($files);

print_r($files);
?>

Output:

Array
(
    [0] => file1.txt
    [1] => file2.txt
    [2] => file10.txt
)

Sort Multidimensional Array by Column

When you have an array of rows, you may want to sort it by one column, such as price, name, or date.

Use array_column() with array_multisort() for this. The array_column() function extracts the column used for sorting.

<?php
$products = [
    ["name" => "Keyboard", "price" => 1200],
    ["name" => "Mouse", "price" => 600],
    ["name" => "Monitor", "price" => 9500]
];

$prices = array_column($products, "price");

array_multisort($prices, SORT_ASC, $products);

print_r($products);
?>

Output:

Array
(
    [0] => Array
        (
            [name] => Mouse
            [price] => 600
        )

    [1] => Array
        (
            [name] => Keyboard
            [price] => 1200
        )

    [2] => Array
        (
            [name] => Monitor
            [price] => 9500
        )
)

Custom Sorting with usort()

Use usort() when the built-in sorting functions are not enough. It lets you write your own comparison logic.

For example, the following code sorts products by price from low to high.

<?php
$products = [
    ["name" => "Keyboard", "price" => 1200],
    ["name" => "Mouse", "price" => 600],
    ["name" => "Monitor", "price" => 9500]
];

usort($products, function ($first, $second) {
    return $first["price"] <=> $second["price"];
});

print_r($products);
?>

Output:

Array
(
    [0] => Array
        (
            [name] => Mouse
            [price] => 600
        )

    [1] => Array
        (
            [name] => Keyboard
            [price] => 1200
        )

    [2] => Array
        (
            [name] => Monitor
            [price] => 9500
        )
)

The spaceship operator <=> returns -1, 0, or 1 based on the comparison. This makes custom sorting code short and readable.

You can read more about comparison operators in the official PHP comparison operators documentation.

Find a Value Before Sorting

Sometimes, you may want to check if a value exists before sorting or displaying an array. For that, use in_array().

<?php
$categories = ["PHP", "JavaScript", "MySQL"];

if (in_array("PHP", $categories, true)) {
    sort($categories);
    print_r($categories);
}
?>

If you want to learn this check in detail, read the PHP in_array tutorial.

Common Mistakes and Fixes

1. Using sort() on associative arrays

sort() resets keys. This can break the meaning of an associative array.

<?php
$productPrices = [
    "Keyboard" => 1200,
    "Mouse" => 600
];

sort($productPrices);

print_r($productPrices);
?>

Output:

Array
(
    [0] => 600
    [1] => 1200
)

Fix: Use asort() when you want to sort values and preserve keys.

2. Forgetting that sort functions modify the original array

Most PHP sorting functions sort the array in place. They change the original array and return true or false, not the sorted array.

<?php
$numbers = [30, 10, 20];

$result = sort($numbers);

var_dump($result);
print_r($numbers);
?>

Fix: Call the sort function first, then use the original array variable.

3. Expecting natural order from sort()

sort() does not always sort numbered strings in the way humans expect.

Fix: Use natsort() for file names, labels, and strings with numbers.

Security Considerations

Sorting an array is not a security feature by itself. But sorted data is often displayed in tables, reports, or admin screens. So you still need to handle the data safely.

  • Validate user-selected sort fields before using them.
  • Do not allow raw user input to decide function names or array keys without checking.
  • Escape output with htmlspecialchars() before showing sorted values in HTML.
  • Use prepared statements if the sorted data is later used in database queries.

For example, if a user selects a sort option from a dropdown, compare it against an allowed list before applying it.

<?php
$allowedSortFields = ["name", "price"];

$sortBy = $_GET["sort"] ?? "name";

if (!in_array($sortBy, $allowedSortFields, true)) {
    $sortBy = "name";
}
?>

This small check prevents unexpected values from entering your sorting logic.

Complete Example: Sort Products by Price

This example shows a small product list sorted by price. It uses a safe list of allowed sort fields and then sorts the array based on the selected option.

<?php
$products = [
    ["name" => "Keyboard", "price" => 1200],
    ["name" => "Mouse", "price" => 600],
    ["name" => "Monitor", "price" => 9500]
];

$allowedSortFields = ["name", "price"];
$sortBy = $_GET["sort"] ?? "price";

if (!in_array($sortBy, $allowedSortFields, true)) {
    $sortBy = "price";
}

usort($products, function ($first, $second) use ($sortBy) {
    return $first[$sortBy] <=> $second[$sortBy];
});
?>

<table>
    <thead>
        <tr>
            <th>Product</th>
            <th>Price</th>
        </tr>
    </thead>
    <tbody>
        <?php foreach ($products as $product): ?>
            <tr>
                <td><?php echo htmlspecialchars($product["name"]); ?></td>
                <td><?php echo htmlspecialchars((string) $product["price"]); ?></td>
            </tr>
        <?php endforeach; ?>
    </tbody>
</table>

This example shows three useful ideas:

  • Use an allowed list before accepting a sort field.
  • Use usort() when sorting rows by a selected column.
  • Escape output before displaying values in HTML.
PHP array sort products by price demo output

Demo output showing PHP array sorting products by price.

Screenshot to capture: Run the demo project and capture the product table sorted by price. One screenshot is enough.

Developer FAQ

What is the difference between sort() and asort()?

sort() sorts values and resets numeric keys. asort() sorts values but preserves the original keys.

When should I use ksort()?

Use ksort() when you want to sort an associative array by its keys.

Does sort() return the sorted array?

No. PHP sorting functions usually modify the original array and return true or false.

How do I sort an array in descending order?

Use rsort() for indexed arrays, arsort() for associative arrays sorted by value, and krsort() for associative arrays sorted by key.

How do I sort a multidimensional array by price or name?

Use array_multisort() with array_column(), or use usort() with a custom comparison function.

Conclusion

PHP gives several sorting functions because arrays can be used in different ways. Use sort() for simple indexed arrays, asort() when keys must be preserved, and ksort() when you want to sort by key.

For real project data, especially arrays of rows, usort() is often the most flexible option. It lets you sort by price, name, date, or any other field with clear custom logic.

The key point is to choose the sorting function based on whether you are sorting values or keys, and whether the original keys should be preserved.

Download Source Code

Download the complete PHP array sort demo project and run it locally.

Download the PHP array sort demo project

The project includes a simple product sorting table, clean PHP code, light CSS, and setup instructions. No database is required.

Photo of Vincy, PHP developer
Written by Vincy Last updated: May 2, 2026
I'm a PHP developer with 20+ years of experience and a Master's degree in Computer Science. I build and improve production PHP systems for eCommerce, payments, webhooks, and integrations, including legacy upgrades (PHP 5/7 to PHP 8.x).

Continue Learning

These related tutorials may help you continue learning.

Leave a Reply

Your email address will not be published. Required fields are marked *

Explore topics
Need PHP help?