PHP uksort

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:

  • $array is the input array.
  • $callback is the comparison function that determines the order of keys.

Here’s the syntax of the callback function:

callback(mixed $x, mixed $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($x) <=> strtolower($y)
);

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

Output:

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

Summary

  • Use the uksort() function to sort an array by key using a user-defined comparison function.
Did you find this tutorial useful?