How to sort associative array in PHP

Last Updated on

CraftyTechie is reader-supported. When you buy through links on our site, we may earn an affiliate commission.

In the article about how to sort an array in PHP,  we saw several functions for sorting an array. Some of these functions are useful for sorting an associative array, either by key or by value. Here’s a throwback to those functions.

  • asort() – Sorts an associate array by value, in ascending order.
  • arsort() – Sorts an associative array by value, in descending order.
  • ksort() – Sorts an associate array by key, in ascending order.
  • krsort() – Sorts an associate array by key, in descending order.

In this article about how to sort associative array in PHP, we’ll extend upon the previous article and see some more advanced functions. These functions are usually helpful in sorting multi-dimensional associative arrays. We’ll be using an array of inventory items in the examples.

Inventory Items

Here’s how the array looks like.

$inventory_items = array(
    array("ProductName"=>"White Sneakers","InStock"=>25,"Price(USD)"=>100),
    array("ProductName"=>"Metal Ring","InStock"=>15,"Price(USD)"=>50),
    array("ProductName"=>"Denim Jeans","InStock"=>10,"Price(USD)"=>40),
    array("ProductName"=>"Wooden Table","InStock"=>7,"Price(USD)"=>132),
    array("ProductName"=>"Gaming Chair","InStock"=>8,"Price(USD)"=>200),
);

What if we need to sort these products by Price(USD) or InStock? The functions listed above won’t help us get around this problem. So, we’ll see functions that would help in sorting this multi-dimensional inventory items array.

Option#1 – Sort associative array using usort function

PHP usort function takes a function as an argument and thus, sorts an array based on the return value of that function. 

Description

Sorts an array by values based on a user-defined function.

usort(array &$array, callable $callback): bool

Arguments

  • $array      – Array to be sorted
  • $callback User-defined comparison function 

Return Types

The function always returns true.

The callback function

The $callback is a crucial argument of usort. It is a user-defined function that returns values less than, equal to, or greater than zero depending if the first value is less than, equal to, or greater than the second value. Here’s the function signature.

callback(mixed $a, mixed $b): int

 We’ll define a function for usort that will sort the array by Price(USD).

//Callback function for usort
function sortByPrice($item1,$item2)
{
    //If the prices are same return 0.
    if($item1["Price(USD)"] == $item2["Price(USD)"]) return 0;
    //If price of $item1 < $item2 then return -1 else return 1.
    return $item1['Price(USD)'] < $item2['Price(USD)'] ? -1 : 1;
}

Example

Next, we’ll pass the inventory items array to usort along with the callback function. 

//usort will sort this array by Price(USD)
usort($inventory_items,"sortByPrice");

Here’s the output.

/*
OUTPUT
Array
(
    [0] => Array
        (
            [ProductName] => Denim Jeans
            [InStock] => 10
            [Price(USD)] => 40
        )
 
    [1] => Array
        (
            [ProductName] => Metal Ring
            [InStock] => 15
            [Price(USD)] => 50
        )
 
    [2] => Array
        (
            [ProductName] => White Sneakers
            [InStock] => 25
            [Price(USD)] => 100
        )
 
    [3] => Array
        (
            [ProductName] => Wooden Table
            [InStock] => 7
            [Price(USD)] => 132
        )
 
    [4] => Array
        (
            [ProductName] => Gaming Chair
            [InStock] => 8
            [Price(USD)] => 200
        )
 
)
*/

The inventory items are sorted in ascending order. It is also possible in descending order too. However, we’ll leave it for you. 

Hint: Modify the callback function to change the sorting order.

You’re aware of usort and, most importantly, the callback function. Thus, you can test yourself by defining a callback function for sorting the same array by InStock. Pat yourself on the back if you’re able to do this challenge.

For PHP 7+ users

Before moving to the next function, here’s a quick note for PHP 7+ users. You can use the spaceship operator to simplify the callback function. Here’s how to reproduce the same callback function with the spaceship operator.

//Callback function for usort
function sortByPrice($item1,$item2)
{
    
    if($item1["Price(USD)"] <==> $item2["Price(USD)"]) return 0;
    
}

The spaceship operator is <==>, and it returns 0 if both the operands are equal, 1 if the left operand is greater, and -1 if the right operand is greater.

Option#2 – Sort associative array using array_multisort

PHP array_multisort is yet another helpful function for sorting multi-dimensional associative arrays. 

Description

Sorts multi-dimensional or multiple arrays.

array_multisort(
    array &$array1,
    mixed $array1_sort_order = SORT_ASC,
    mixed $array1_sort_flags = SORT_REGULAR,
    mixed ...$rest
): bool

Arguments

  • &$array1 – An array being sorted
  • $array1_sort_order The sorting order of the previous array argument. By default, it is SORT_ASC
  • $array1_sort_flags –  Flag for specifying the mode of sorting. By default, SORT_REGULAR
  • $rest – Array’s elements corresponding to the previous array argument are compared. 

Return Type

Returns true on success and false on failure.

Example

Here’s an example of using the array_multisort function.

//Define an array for prices.
$prices = array();
 
//Loop through the array to get prices in the prices array.
foreach($inventory_items as $key=>$value)
{
    $prices[$key] = $value["Price(USD)"];
}
 
array_multisort($prices,$inventory_items);
 
print_r($inventory_items);

Here’s the output.

Array
(
    [0] => Array
        (
            [ProductName] => Denim Jeans
            [InStock] => 10
            [Price(USD)] => 40
        )

    [1] => Array
        (
            [ProductName] => Metal Ring 
            [InStock] => 15
            [Price(USD)] => 50
        )

    [2] => Array
        (
            [ProductName] => White Sneakers
            [InStock] => 25
            [Price(USD)] => 100
        )

    [3] => Array
        (
            [ProductName] => Wooden Table
            [InStock] => 7
            [Price(USD)] => 132
        )

    [4] => Array
        (
            [ProductName] => Gaming Chair
            [InStock] => 8
            [Price(USD)] => 200
        )

)

The array is sorted in ascending order. We can see a foreach loop in the code for extracting the prices in an array of its own. In PHP version 5.5.0 and beyond, the foreach loop can be replaced with array_column. Thus, this function does the same job as the foreach does here.

Sort associative array by keys using uksort

PHP uksort function is similar to usort except that it sorts the array by keys. The anatomy of the function is pretty much similar to the usort. So, let’s use it to sort an associative array by key.

<?php
$names_score = array("Edward"=>10,"Bob"=>20,"Kylie"=>30,"Robert"=>40,"William Shakespear"=>50);
 
 
//Callback function for uksort
function sortByLength($key1,$key2)
{
    //If the prices are same return 0.
    if(strlen($key1) == strlen($key2)) return 0;
    //If length of $key1 < $key2 then return -1 else return 1.
    return strlen($key1) > strlen($key2) ? -1 : 1;
}
 
 
uksort($names_score,"sortByLength");
 
print_r($names_score);
 
/*
OUTPUT
Array
(    
    [William Shakespear] => 50
    [Edward] => 10
    [Robert] => 40
    [Kylie] => 30
    [Bob] => 20
)
*/
?>

The callback function compares the name’s strings by length. Finally, uksort sorts the array by keys in descending order.

Conclusion

Besides the functions that we had seen in a previous article, in this article, we’ve seen usort and array_multisort functions for sorting a multi-dimensional associative array. We have also seen uksort for sorting an array by key values. So hopefully, you might have learned something new today. Stay tuned for more awesome PHP articles.

Want to explore more useful PHP tutorials?

We have many fun articles related to PHP. You can explore these to learn more about PHP.

PHP serialize vs json_encode

How to take form inputs and put them into a PHP associative array

How to put values in an associative array into another array in PHP

Did you find this article helpful?

Join the best weekly newsletter where I deliver content on building better web applications. I curate the best tips, strategies, news & resources to help you develop highly-scalable and results-driven applications.

Build Better Web Apps

I hope you're enjoying this article.

Get the best content on building better web apps delivered to you.