Sort an array in reverse order with PHP

Josh Sherman
1 min read
Software Development PHP

Arrays are a great way to store / work with data. In PHP, arrays are one of the most powerful data types of available. From time to time, you need to sort an array in reverse order. Of course, PHP has you covered:

$array = [
    1 => 'one',
    2 => 'two',
    3 => 'three',
    4 => 'four',
    5 => 'five',
];

rsort($array);

print_r($array);

Great, the array values are now sorted in reverse order. But wait?! The keys for those values have been reset! What are we to do? Again, PHP has you covered:

$array = [
    1 => 'one',
    2 => 'two',
    3 => 'three',
    4 => 'four',
    5 => 'five',
];

arsort($array);

print_r($array);

BOOM! Now the array values are sorted in reverse order and the keys have been retained. This can be very important when you are utilizing both the array’s values as well as the keys for separate things.

The trick is making sure you sort your data based on how you plan to use it. I’ve personally been burned by incorrectly sorting data, but it’s always been simple to troubleshoot and resolve.

Join the Conversation

Good stuff? Want more?

Weekly emails about technology, development, and sometimes sauerkraut.

100% Fresh, Grade A Content, Never Spam.

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Head of Engineering and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.

Currently Reading

Parasie Eve

Previous Reads

Buy Me a Coffee Become a Sponsor

Related Articles