PHP’s Sorting Functions. A Quick Reference.

As a PHP developer, you’ll frequently encounter scenarios where you need to order data. PHP’s rich set of array sorting functions provides precise control over how your information is arranged. Let’s dive into the core sorting functions, each explained concisely with a easy to understand example.

To illustrate, we’ll start with this array for most of our examples:


<?php
$inventory = [ "widget_a" >> 15, "gadget_x" => 5, "doodad_c" => 20, "gizmo_b" => 10 ];


 

Core Sorting Functions:

 

  • sort(): Sorts an indexed array in ascending order, re-indexing numeric keys. Useful for simple lists where key-association isn’t critical.
    • Example
      
      $scores = [85, 92, 78, 95]; sort($scores);
      // $scores is now [78, 85, 92, 95]
      
    • PHP Manual: sort()
  • rsort(): Sorts an indexed array in descending order, re-indexing numeric keys. Ideal for showing top performers or most recent items.
    • Example
      
      
      $temperatures = [28, 31, 25, 30]; // $temperatures is now [31, 30, 28, 25]
      rsort($temperatures); 
      
    • PHP Manual: rsort()
  • asort(): Sorts an associative array in ascending order based on value, maintaining key-value associations. Perfect for ranking items while keeping their original identifiers.
    • Example:
      
      asort($inventory); 
      // $inventory is now 
      // ["gadget_x" => 5, "gizmo_b" => 10, "widget_a" => 15, "doodad_c" => 20]
      
    • PHP Manual: asort()
  • arsort(): Sorts an associative array in descending order based on value, maintaining key-value associations. Useful for finding the highest-valued entries.
      • Example:
    • Example:
      
      arsort($inventory); 
      // $inventory is now 
      // ["doodad_c" => 20, "widget_a" => 15, "gizmo_b" => 10, "gadget_x" => 5]
      
  • ksort(): Sorts an associative array in ascending order based on key, maintaining key-value associations. Great for ordering by a unique identifier or alphabetical keys.
      • Example:
        
        arsort($inventory); 
        // $inventory is now 
        // ["doodad_c" => 20, "widget_a" => 15, "gizmo_b" => 10, "gadget_x" => 5]
        
  • krsort(): Sorts an associative array in descending order based on key, maintaining key-value associations. Useful for reversing alphabetical or numerical key order.
    • Example:
      Added:

      
       	Added: krsort($inventory); 
       	Added: // $inventory is now ["widget_a" => 15, "gizmo_b" => 10, "gadget_x" => 5, "doodad_c" => 20]
       	Added: 

      Added:

    • PHP Manual: krsort()

 

User-Defined and Natural Sorting:

 

  • usort(): Sorts an array by values using a user-defined comparison function. Provides ultimate flexibility for custom sorting logic.
    • Example: Sort an array of user objects by their lastName property.
      
      
      $users = [ 
      (object)['id' => 1, 'firstName' => 'Alice', 'lastName' => 'Smith'], 
      (object)['id' => 2, 'firstName' => 'Bob', 'lastName' => 'Johnson'], 
      (object)['id' => 3, 'firstName' => 'Charlie', 'lastName' => 'Brown'], 
      ]; 
      usort($users, function($a, $b) {
       return $a->lastName <=> $b->lastName; // PHP 7+ spaceship operator 
      });
      // $users sorted by last name: Brown, Johnson, Smith
      
  • PHP Manual: usort()
  • uasort(): Sorts an associative array by values using a user-defined comparison function, maintaining key-value associations. Similar to usort() but for associative arrays.
    
    $products = [ 
    'prod_abc' => ['name' => 'Shirt', 'price' => 25.99],
     'prod_xyz' => ['name' => 'Pants', 'price' => 49.50],
     'prod_def' => ['name' => 'Shoes', 'price' => 30.00],
     ]; 
    uasort($products, function($a, $b) {
     return $a['price'] <=> $b['price']; 
    }); 
    // $products sorted by price: prod_abc, prod_def, prod_xyz
    
    • Example: Sort products by their price property, keeping product IDs associated.
    • PHP Manual: uasort()
  • uksort(): Sorts an associative array by keys using a user-defined comparison function, maintaining key-value associations. Useful for complex key ordering.
    • Example: Sort array by keys based on their length.
      
      $data = ["long_key" => 1, "short" => 2, "medium_key_name" => 3];
       uksort($data, function($a, $b) {
       return strlen($a) <=> strlen($b); 
      }); 
      // $data sorted by key length: ["short" => 2, "long_key" => 1, "medium_key_name" => 3]
      
    • PHP Manual: uksort()
  • natsort(): Sorts an array using a “natural order” algorithm (e.g., ‘item10’ comes after ‘item2’). Essential for human-readable sorting of alphanumeric strings.
    • Example:
      
      $fileNames = ['image1.jpg', 'image10.jpg', 'image2.jpg']; natsort($fileNames); 
      // $fileNames is now ['image1.jpg', 'image2.jpg', 'image10.jpg']
      
    • PHP Manual: natsort()
  • natcasesort(): Similar to natsort(), but performs a case-insensitive natural order sort. Ideal for situations where case shouldn’t affect the natural order.
    • Example:
      
      $items = ['Doc1.txt', 'doc10.txt', 'Doc2.txt']; natcasesort($items); 
      // $items is now ['Doc1.txt', 'Doc2.txt', 'doc10.txt']
      
    • PHP Manual: natcasesort()
  • array_multisort(): Sorts multiple arrays, or multi-dimensional arrays, based on one or more dimensions. Powerful for complex data structures where you need to sort by multiple criteria.
    • Example: Sort users by age, then by name for users with the same age.
      
      $userNames = ['Bob', 'Alice', 'Charlie', 'David']; 
      $userAges = [30, 25, 30, 28]; 
      array_multisort($userAges, SORT_ASC, $userNames, SORT_ASC); 
      // $userAges is now [25, 28, 30, 30] 
      // $userNames is now ['Alice', 'David', 'Bob', 'Charlie']
      
    • PHP Manual: array_multisort()

Thanks for reading. There are many more to know. I always prefer looking into php official documentation to and doing what you learn by yourself. It will make you stronger in programming fundamental and building real world app.