Sorting a 2D Array by Column in PHP: Under the Hood Analysis

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

The Magic of Sorting: How PHP Orders Two-Dimensional Arrays

\n\n

Imagine: you have a table with data — a list of users, products, or orders. You need to sort it by age, price, or date. In Excel, this is done with one click. And in PHP? That's where the interesting part begins. The question "Sort a 2d array by a column value" on Stack Overflow has garnered thousands of views for a reason — it's one of those tasks every developer faces.

\n\n

Today, we won't just provide ready-made code. We'll look "under the hood" of PHP and understand how the mechanisms of sorting a multidimensional array actually work. You'll learn why usort is faster than loops, how PHP compares elements, and what pitfalls await a beginner. Let's go!

\n\n

The Problem: Why Sorting a 2D Array Is Not Trivial?

\n\n

PHP has sort() and asort() for one-dimensional arrays. But when the array becomes two-dimensional (an array of arrays), the standard functions fall short. Why? Because PHP doesn't know which specific "column" (key of the inner array) you want to sort by.

\n\n

Here's a typical example:

\n\n
<?php\n$users = [\n    ['name' => 'Anna', 'age' => 25],\n    ['name' => 'Ivan', 'age' => 30],\n    ['name' => 'Maria', 'age' => 22]\n];\n// How to sort by age?\n?>
\n\n

Just call sort($users)? No — PHP will issue a warning and do something unintended. A smarter approach is needed.

\n\n

Solution #1: Classic usort with a Custom Function

\n\n

The most popular way is to use usort(). This function takes an array and a callback function that determines the sort order. Let's break it down "under the hood".

\n\n

How does usort work?

\n\n

When you call usort($array, $callback), PHP does the following:

\n
    \n
  • Splits the array into pairs of elements.
  • \n
  • For each pair, it calls your callback function.
  • \n
  • The callback must return: a negative number (if the first element is "less"), zero (if equal), a positive number (if the first is "greater").
  • \n
  • Based on these responses, PHP rearranges the elements using the Quicksort algorithm or its hybrid.
  • \n
\n\n

Here's what it looks like in code:

\n\n
<?php\n$users = [\n    ['name' => 'Anna', 'age' => 25],\n    ['name' => 'Ivan', 'age' => 30],\n    ['name' => 'Maria', 'age' => 22]\n];\n\nusort($users, function($a, $b) {\n    return $a['age'] - $b['age'];\n});\n\nprint_r($users);\n// Result: Maria (22), Anna (25), Ivan (30)\n?>
\n\n

Notice: we subtract $b's age from $a's. If $a['age'] is smaller — the result is negative, element $a comes first. Simple as can be.

\n\n

Pitfall: Strings and Case Sensitivity

\n\n

If you're sorting by a string field (e.g., name), subtraction won't work. You need to use strcmp() or strcasecmp() for case-insensitive sorting:

\n\n
<?php\nusort($users, function($a, $b) {\n    return strcmp($a['name'], $b['name']);\n});\n// Sort by name (Anna, Ivan, Maria)\n?>
\n\n

But be careful: strcmp() is case-sensitive. "apple" and "Apple" will be considered different. If this matters — use strcasecmp().

\n\n

Solution #2: array_multisort — Powerful but Tricky

\n\n

The second popular method is array_multisort(). This function can sort multiple arrays at once or a multidimensional array by one column. "Under the hood" it works differently: it extracts the column, sorts it, and then rearranges the other arrays in the same order.

\n\n

Here's what it looks like:

\n\n
<?php\n$users = [\n    ['name' =&g                

Blogs

Book Recommendations