Sorting is a topic most of us “tick off” at university and only return to during job interviews. Yet understanding how sorting algorithms work helps make better decisions in everyday PHP and database work. I walk through a few classic approaches, implement them in PHP, and show where this has real practical relevance.
Bubble Sort – slow but readable
Complexity: O(n²) – at 1000 elements that is a million comparison operations.
<?php
function bubbleSort(array $arr): array
{
$n = count($arr);
for ($i = 0; $i < $n - 1; $i++) {
$swapped = false;
for ($j = 0; $j < $n - $i - 1; $j++) {
if ($arr[$j] > $arr[$j + 1]) {
[$arr[$j], $arr[$j + 1]] = [$arr[$j + 1], $arr[$j]];
$swapped = true;
}
}
if (!$swapped) break;
}
return $arr;
}
print_r(bubbleSort([64, 34, 25, 12, 22, 11, 90]));
// [11, 12, 22, 25, 34, 64, 90]
Merge Sort – divide and conquer
Complexity: O(n log n).
<?php
function mergeSort(array $arr): array
{
$n = count($arr);
if ($n <= 1) return $arr;
$mid = (int) ($n / 2);
$left = mergeSort(array_slice($arr, 0, $mid));
$right = mergeSort(array_slice($arr, $mid));
return merge($left, $right);
}
function merge(array $left, array $right): array
{
$result = []; $i = 0; $j = 0;
while ($i < count($left) && $j < count($right)) {
$result[] = $left[$i] <= $right[$j] ? $left[$i++] : $right[$j++];
}
while ($i < count($left)) $result[] = $left[$i++];
while ($j < count($right)) $result[] = $right[$j++];
return $result;
}
PHP's built-in sort() and usort()
<?php
// Simple array
$data = [3, 1, 4, 1, 5, 9, 2, 6];
sort($data); // [1, 1, 2, 3, 4, 5, 6, 9]
// Associative array by value - preserves keys
$prices = ['apple' => 1.5, 'banana' => 0.9, 'cherry' => 3.2];
asort($prices); // banana, apple, cherry
// Sorting objects by field
$products = [
['name' => 'Widget', 'price' => 29.99],
['name' => 'Gadget', 'price' => 9.99],
];
usort($products, fn($a, $b) => $a['price'] <=> $b['price']);
The spaceship operator (<=>) - PHP 7.x
<?php // Multi-level sort - first by price, then alphabetically usort($products, fn($a, $b) => [$a['price'], $a['name']] <=> [$b['price'], $b['name']]);
When does this matter in practice?
- Sorting 10,000 products in PHP in a loop instead of a single
ORDER BY- O(n log n) in PHP vs indexed sorting in the database - Using
in_array()in a loop on large arrays - O(n²) instead of an associative array withisset()- O(n)
Summary
Know your algorithms - not to implement them from scratch in production code, but to understand what the framework and the database are doing for you.
