Get your next remote job on LaraJobs.
1 contributor Edit on GitHub PHP

Learn how to sort any kind of array in PHP

Table of contents:

Learn how to sort any kind of array in PHP

Sorting arrays is a common task in PHP, and the language provides a variety of functions to order elements just the way you need.

Whether you’re dealing with numerical indices or associative arrays, PHP has you covered. 😎

Let me show you some of PHP’s array sorting capabilities.

Utilizing the sort() and rsort() Functions

When you have a simple indexed array that needs reordering, sort() and rsort() are the straightforward choices for ascending and descending order, respectively.

For sort():

$fruits = ["Banana", "Apple", "Orange"];
 
sort($fruits);
 
var_dump($fruits);

Once sorted, the $fruits array will be:

["Apple", "Banana", "Orange"]

Now, what to do when you have an associative array? The sort() function won’t cut it.

Maintaining key association with asort() and arsort()

Associative arrays require maintaining the relationship between keys and values. asort() sorts in ascending order by value, maintaining key association, and arsort() does the same in descending order.

Example of asort():

$prices = [
"Apple" => 1.2,
"Banana" => 0.5,
"Orange" => 0.9,
];
 
asort($prices);
 
var_dump($prices);

The sorted $prices array now looks like this:

[
"Banana" => 0.5,
"Orange" => 0.9,
"Apple" => 1.2,
]

Key-centric sorting with ksort() and krsort()

To sort an associative array by its keys, ksort() for ascending order and krsort() for descending order are your go-to functions.

Using ksort():

$products = [
"product3" => "Chair",
"product1" => "Desk",
"product2" => "Lamp",
];
 
ksort($products);
 
var_dump($products);

Custom sorting with usort(), uasort(), and uksort()

What we saw until now will probably cover 99% of your needs.

But sometimes, you need a sorting logic that’s not built-in. For these instances, usort() for value-based, uasort() for value-based with preserved keys, and uksort() for key-based custom sorting. Each requires a user-defined comparison function.

An example with usort():

$numbers = [3, 2, 5, 6, 1];
 
usort($numbers, function ($a, $b) {
return $a <=> $b; // The spaceship operator
});
 
var_dump($numbers);

With the custom function, $numbers will be sorted as:

[1, 2, 3, 5, 6];

Of course, in that case, using sort() would be better. I just wanted to let you know that custom sorting logic is possible! 🙂

Benjamin Crozat

Written by Benjamin Crozat

Indie hacker, blogger, and AI enthusiast building things with the TALL stack. 🔥

Follow me on:

Recommended articles

Bring order back to your PHP arrays using array_values() Bring order back to your PHP arrays using array_values()

Discover how array_values() in PHP can help you re-do what has been undone.

Published on Nov 11, 2023

PHP
Sort your Laravel Eloquent queries results using orderBy() Sort your Laravel Eloquent queries results using orderBy()

Master Laravel's Eloquent `orderBy()`. Explore multiple columns sorting, the advanced `orderByRaw()`, and `reorder()`.

Published on Sep 9, 2023

console.log() in PHP console.log() in PHP

Explore the world of PHP debugging with var_dump(), and Laravel's friendlier alternatives, dump() and dd(). Much charm, such useful!

Modified on Sep 6, 2023

PHP
20+ Laravel best practices, tips and tricks to use in 2023 20+ Laravel best practices, tips and tricks to use in 2023

Learning a framework can be overwhelming, but time and execution will make you a master. Here are some best practices to help you toward your goal.

Modified on Oct 17, 2023

Making sense of PHP's array_map() function Making sense of PHP's array_map() function

PHP's array_map() is an extremely useful function that will help you write better code. Let me demystify it for you.

Published on Nov 4, 2023

PHP
Print an array with PHP (+ Laravel) Print an array with PHP (+ Laravel)

Debugging requires dissecting everything. Here's a list of all the one-line of code built-in ways to print arrays in PHP (and even Laravel-specific helpers).

Modified on Jun 24, 2023

Gold sponsors New

  • Wire Elements
    Beautiful handcrafted Livewire components.
    Check site
Your business here

Partners

If you buy from one of my partners below, I will be compensated at no cost to you. These are services I use or used, and 100% stand behind.

  • Scalable and reliable VPS hosting.
    Bonus: $200 of free credits
    Check site
  • The Google Analytics alternative without compromise.
    Free trial: 30 days
    Bonus: $10 off your first invoice
    Check site
  • Flare
    Track PHP and JavaScript errors in one place.
    Free trial: 10 days
    Check site
  • Keep track of your Google rankings.
    Free trial: 7 days
    Promo code: WELCOME30
    Check site
- / -