PHP uksort Function (original) (raw)

Skip to content

Summary: in this tutorial, you’ll learn how to use the PHP uksort() function to sort an array by keys using a user-defined comparison function.

Introduction to the PHP uksort() function #

The uksort() function allows you to sort an array by key using a user-defined comparison function. Typically, you use the uksort() function to sort the keys of an associative array.

The following shows how to use the uksort() function’s syntax:

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

The uksort() function has two parameters:

Here’s the syntax of the callback function:

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 less than, equal to, or greater than zero if $x is less than, equal to, or greater than $y.

The uksort() function returns a boolean value, true on success or false on failure.

The PHP uksort() function example #

The following example shows how to use the uksort() function to sort the keys of the $name array case-insensitively:

`<?php

$names = [ 'c' => 'Charlie', 'A' => 'Alex', 'b' => 'Bob' ];

uksort( $names, fn ($x, y)=>strtolower(y) => strtolower(y)=>strtolower(x) <=> strtolower($y) );

print_r($names);`Code language: PHP (php)

Try it

Output:

Array ( [A] => Alex [b] => Bob [c] => Charlie )Code language: PHP (php)

Summary #

Did you find this tutorial useful?