Skip to content

PHP By Exalogics

A Simple Easy Site to Learn, Understand and create php

Menu
  • Home
  • Welcome to php by Exalogics
    • Introduction to PHP
    • How to Install PHP on Windows
    • PHP Variables
    • PHP Constants
    • PHP Switch Statement
    • PHP Data Types
    • PHP Operators
    • PHP If Else Statements
    • PHP E-Commerce Development
    • Your First PHP Script
    • PHP Error Handling
    • PHP Frameworks Guide
    • PHP MySQL Database Development
    • PHP Security Best Practices
    • PHP CMS Development
    • PHP Hosting Guide
  • PHP API Development
Menu

How to Sort Arrays in PHP

Posted on October 20, 2026






How to Sort Arrays in PHP – A Complete Guide



How to Sort Arrays in PHP

Sorting arrays is one of the most common tasks in PHP development. Whether you’re dealing with simple numeric lists, associative arrays, or complex multidimensional structures, PHP offers a rich set of functions to sort data efficiently. This guide walks you through the core sorting functions, custom sorting techniques, and performance considerations to help you write clean, maintainable code.

Table of Contents

  • Basic Sorting Functions
  • Sorting Associative Arrays
  • Custom Sorting with Callbacks
  • Sorting Multidimensional Arrays
  • Performance Tips & Common Pitfalls

Basic Sorting Functions

For simple indexed arrays, PHP provides three primary functions that differ in how they treat keys and order:

sort() – Ascending Value Sort

$numbers = [5, 2, 9, 1];
sort($numbers); // $numbers becomes [1, 2, 5, 9]

sort() reindexes the array, discarding original keys. Use it when the numeric index does not matter.

rsort() – Descending Value Sort

$numbers = [5, 2, 9, 1];
rsort($numbers); // $numbers becomes [9, 5, 2, 1]

shuffle() – Random Order

$cards = range(1, 52);
shuffle($cards); // Randomizes the order of $cards

Sorting Associative Arrays

When you need to preserve keys, PHP offers asort(), arsort(), ksort(), and krsort().

asort() – Ascending Value Sort (maintains keys)

$scores = ['Alice' => 85, 'Bob' => 92, 'Carol' => 78];
asort($scores);
// Result: ['Carol' => 78, 'Alice' => 85, 'Bob' => 92]

arsort() – Descending Value Sort (maintains keys)

arsort($scores);
// Result: ['Bob' => 92, 'Alice' => 85, 'Carol' => 78]

ksort() – Ascending Key Sort

ksort($scores);
// Result: ['Alice' => 85, 'Bob' => 92, 'Carol' => 78]

krsort() – Descending Key Sort

krsort($scores);
// Result: ['Carol' => 78, 'Bob' => 92, 'Alice' => 85]

Custom Sorting with Callbacks

For more complex criteria, PHP’s usort(), uasort(), and uksort() let you define a comparison function.

usort() – Sort by Value with a User‑Defined Callback

$people = [
    ['name' => 'Alice', 'age' => 30],
    ['name' => 'Bob',   'age' => 25],
    ['name' => 'Carol', 'age' => 35],
];

usort($people, function($a, $b) {
    return $a['age'] <=> $b['age']; // Spaceship operator (PHP 7+)
});
// $people is now ordered by age ascending

uasort() – Preserve Keys While Using a Callback

$items = [
    'a' => 3,
    'b' => 1,
    'c' => 2,
];

uasort($items, function($x, $y) {
    return $x <=> $y;
});
// Keys remain ['b', 'c', 'a'] after sorting by value

uksort() – Sort by Keys Using a Callback

uksort($items, function($k1, $k2) {
    return strcmp($k2, $k1); // Reverse alphabetical order
});

Sorting Multidimensional Arrays

When dealing with arrays of arrays (e.g., database result sets), array_multisort() or usort() with a custom comparator are the go‑to solutions.

array_multisort() – Sort by One or More Columns

 3, 'price' => 9.99],
    ['id' => 1, 'price' => 5.50],
    ['id' => 2, 'price' => 7.25],
];

$price = array_column($data, 'price');
$id    = array_column($data, 'id');

array_multisort($price, SORT_ASC, $id, SORT_DESC, $data);
// $data is now sorted by price ASC, then id DESC

usort() for Complex Logic

 'Widget', 'rating' => 4.5, 'sales' => 150],
    ['name' => 'Gadget', 'rating' => 4.7, 'sales' => 120],
    ['name' => 'Doohickey', 'rating' => 4.5, 'sales' => 200],
];

usort($products, function($a, $b) {
    // Primary: rating DESC, Secondary: sales DESC
    $cmp = $b['rating'] <=> $a['rating'];
    if ($cmp === 0) {
        $cmp = $b['sales'] <=> $a['sales'];
    }
    return $cmp;
});

Performance Tips & Common Pitfalls

  • Avoid unnecessary copying: Functions like sort() modify the array in place. Passing a copy (e.g., $sorted = $array; then sort($sorted);) doubles memory usage.
  • Use the most specific function: If you only need to sort values, sort() is faster than asort() because it doesn’t preserve keys.
  • Beware of type juggling: By default, PHP compares values as strings. Use the SORT_NUMERIC flag for numeric sorting: sort($arr, SORT_NUMERIC);
  • Leverage built‑in functions: array_multisort() is implemented in C and is typically faster than a PHP‑level usort() loop for large datasets.
  • Profile with microtime: When optimizing, wrap the sort call in microtime(true) to measure execution time and compare alternatives.

Conclusion

PHP provides a versatile toolbox for sorting arrays, from simple one‑liner functions to fully custom callbacks. By choosing the right function for the job—sort() for indexed lists, asort() for associative values, or usort() for complex logic—you can keep your code readable and performant. Remember to consider key preservation, data types, and memory usage when selecting a sorting strategy.


Leave a Reply Cancel reply

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

Recent Posts

  • Pakistan Tour Zimbabwe 2024 / 2025 / 2026: A Look at the Forthcoming Series
  • How to Sort Arrays in PHP
  • How to Loop Through an Array in PHP (foreach, for)
  • Pakistan Tour Sri Lanka 2026: A Subcontinent Showdown
  • Pakistan Tour New Zealand 2025: Exploring the Kiwi Conditions

Recent Comments

  1. What are Magic Methods in PHP? (__construct, __destruct, __get, etc.) - 93 Travellers Pakistan on What are Magic Methods in PHP? (__construct, __destruct, __get, etc.)
  2. How to Use Traits in PHP - 93 Travellers Pakistan on How to Use Traits in PHP
  3. What is Polymorphism in PHP? - 93 Travellers Pakistan on What is Polymorphism in PHP?
  4. What is Inheritance in PHP? - 93 Travellers Pakistan on What is Inheritance in PHP?
  5. What is Abstraction in PHP? - 93 Travellers Pakistan on What is Abstraction in PHP?

Archives

  • October 2026
  • September 2026
  • August 2026
  • July 2026

Categories

  • PHP Basics
  • Uncategorized
©2026 PHP By Exalogics | Design: Newspaperly WordPress Theme
imunify-bot-check