PHP uasort

Summary: in this tutorial, you’ll learn how to use the PHP uasort() function to sort an associative array.

Introduction to the PHP uasort() function

The uasort() function sorts the elements of an associative array with a user-defined comparison function and maintains the index association.

The following shows the syntax of the uasort() function:

uasort(array &$array, callable $callback): boolCode language: PHP (php)

The uasort() function has two parameters:

  • $array is the input array.
  • $callback is the user-defined comparison function.

The uasort() function returns true on success or false on failure.

The $callback function accepts two parameters:

callback(mixed $x, mixed $y): intCode language: PHP (php)

The $callback function returns an integer. The returned value can be a negative number, zero, and positive number, indicating that $x is less than, equal to, and greater than $y, respectively.

PHP uasort() function

The followning example uses the uasort() function to sort an associative array:

<?php

$countries = [
    'China' => ['gdp' => 12.238 , 'gdp_growth' => 6.9],
    'Germany' => ['gdp' => 3.693 , 'gdp_growth' => 2.22 ],
    'Japan' => ['gdp' => 4.872 , 'gdp_growth' => 1.71 ],
    'USA' => ['gdp' => 19.485, 'gdp_growth' => 2.27 ],
];

// sort the country by GDP
uasort($countries, function ($x, $y) {
    return $x['gdp'] <=> $y['gdp'];
});

// show the array
foreach ($countries as $name => $stat) {
    echo "$name has a GDP of {$stat['gdp']} trillion USD with a GDP growth rate of {$stat['gdp_growth']}%" . '<br>';
}Code language: PHP (php)

Output:

Germany has a GDP of 3.693 trillion USD with a GDP growth rate of 2.22%
Japan has a GDP of 4.872 trillion USD with a GDP growth rate of 1.71%  
China has a GDP of 12.238 trillion USD with a GDP growth rate of 6.9%  
USA has a GDP of 19.485 trillion USD with a GDP growth rate of 2.27%   Code language: plaintext (plaintext)

How it works.

  • First, define an array of countries with the GDP information. The key of each element is the country name. And the value of each element is an array that contains the GDP and GDP growth.
  • Second, sort the $countries array by GDP in ascending order.

Summary

  • Use the uasort() function to sort an associative array with a user-defined comparison function and maintains the index association.
Did you find this tutorial useful?