Learn how to sort any kind of array in PHP

Learn how to sort any kind of array in PHP

Published
Nov 9, 2023
Written by
Benjamin Crozat
0
comments
2 minutes
read

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! 🙂

About Benjamin Crozat
Benjamin Crozat

Hi! I’m from the South of France and I’ve been a self-taught web developer since 2006. When I started learning PHP and JavaScript, PHP 4 was still widely used, Internet Explorer 6 ruled the world, and we used DHTML to add falling snow on websites.

Being able to educate myself for free on the web changed my life for the better. Giving back to the community was a natural direction in my career and I truly enjoy it.

Therefore, I decided to take action:

  1. I launched this blog in September 2022 with the goal to be in everyone’s Google search. I get more than tens of thousands of monthly clicks from it and even more visits overall (my analytics dashboard is public by the way).
  2. I also started growing my X (formerly Twitter) account at the same time, which has now over 7,000 followers.
  3. All the content I write is free thanks to my sponsors.

I also want to be completely free with my time and make a living with my own products. In April 2024, I launched Nobinge, a tool to summarize and chat with your content, including YouTube videos.

Believe me, I’m just getting started!

0 comments

You need to be signed in to comment this post.
Sign in with GitHub