PHP uasort() Function (original) (raw)

Skip to content

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:

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

The $callback function accepts two parameters:

callback(mixed <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>x</mi><mo separator="true">,</mo><mi>m</mi><mi>i</mi><mi>x</mi><mi>e</mi><mi>d</mi></mrow><annotation encoding="application/x-tex">x, mixed </annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.8889em;vertical-align:-0.1944em;"></span><span class="mord mathnormal">x</span><span class="mpunct">,</span><span class="mspace" style="margin-right:0.1667em;"></span><span class="mord mathnormal">mi</span><span class="mord mathnormal">x</span><span class="mord mathnormal">e</span><span class="mord mathnormal">d</span></span></span></span>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.

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′]<=>x['gdp'] <=> x[gdp]<=>y['gdp']; });

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

Try it

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.

Summary #

Did you find this tutorial useful?