PHP / Magento Dev Blog

  • Publikacje
  • O autorze
  • Kontakt

Sorting in PHP – bubble sort, merge sort, usort() and the spaceship operator <=>

by Henryk Tews / Tuesday, 13 November 2018 / Published in Algorytmy

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 with isset() - 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.

About Henryk Tews

What you can read next

Bloom Filter – probabilistic structure, token blacklists, negative cache
Trie – prefix tree, autocomplete, spam filter, benchmark vs array
Quicksort – variants, Introsort, benchmark vs native sort()

© 2026 Created by

TOP
Zarządzaj zgodą
Aby zapewnić jak najlepsze wrażenia, korzystamy z technologii, takich jak pliki cookie, do przechowywania i/lub uzyskiwania dostępu do informacji o urządzeniu. Zgoda na te technologie pozwoli nam przetwarzać dane, takie jak zachowanie podczas przeglądania lub unikalne identyfikatory na tej stronie. Brak wyrażenia zgody lub wycofanie zgody może niekorzystnie wpłynąć na niektóre cechy i funkcje.
Funkcjonalne Always active
Przechowywanie lub dostęp do danych technicznych jest ściśle konieczny do uzasadnionego celu umożliwienia korzystania z konkretnej usługi wyraźnie żądanej przez subskrybenta lub użytkownika, lub wyłącznie w celu przeprowadzenia transmisji komunikatu przez sieć łączności elektronicznej.
Preferencje
Przechowywanie lub dostęp techniczny jest niezbędny do uzasadnionego celu przechowywania preferencji, o które nie prosi subskrybent lub użytkownik.
Statystyka
Przechowywanie techniczne lub dostęp, który jest używany wyłącznie do celów statystycznych. Przechowywanie techniczne lub dostęp, który jest używany wyłącznie do anonimowych celów statystycznych. Bez wezwania do sądu, dobrowolnego podporządkowania się dostawcy usług internetowych lub dodatkowych zapisów od strony trzeciej, informacje przechowywane lub pobierane wyłącznie w tym celu zwykle nie mogą być wykorzystywane do identyfikacji użytkownika.
Marketing
Przechowywanie lub dostęp techniczny jest wymagany do tworzenia profili użytkowników w celu wysyłania reklam lub śledzenia użytkownika na stronie internetowej lub na kilku stronach internetowych w podobnych celach marketingowych.
  • Manage options
  • Manage services
  • Manage {vendor_count} vendors
  • Read more about these purposes
Zobacz preferencje
  • {title}
  • {title}
  • {title}