php

How to Use uksort() Function in PHP

In PHP, sorting refers to arranging the data in a specific order, and the most common orders are numerically and lexicographically. The sorting allows the developers to search the data quickly and optimized the search to a very high level. In PHP, various functions perform sorting based on specific criteria, these functions include asort(), ksort(), and uksort().

In this guide, we will discuss the usage of the uksort() in PHP.

What is uksort() Function in PHP

The uksort() is a function used in PHP for sorting the keys of the arrays according to the user-defined comparison function. It allows you to define your own logic for comparing the keys and sorting them accordingly. If two keys are considered equal by the user-defined function, their relative order in the sorted array will be the same as in the original array. The uksort() function allows us to sort an array by its keys rather than values. It is a helpful tool in PHP to maintain the association between the keys and values in the arrays.

Syntax

The syntax of using the uksort() in PHP is as follows:

uksort($array, callback)

The uksort() function in PHP accepts two compulsory parameters: array and callback. The array specifies the array that needs to be sorted, and the callback is the comparison function string. This uksort() function always returns the bool value True.

Example 1

In the following example code, we have used the uksort() function to sort the array of colors. The user-defined function will sort the array in descending order:

<?php
function colors($a, $b)
{
   if ($a == $b) return 0; {
   return ($a > $b) ? -1 : 1;

   }
}
$input = array("d"=>"orange", "a"=>"black", "b"=>"green" );
uksort($input, "colors");
print_r($input);
?>

Example 2

Suppose we have an array of programming languages, and we can sort them numerically using the uksort() function in PHP from the following code.

<?php
function languages($x, $y)
{
  if ($x == $y)
    return 0;

  return ($x > $y) ? 1 : -1;
}

$names = array(
                "12" => "javascript",
                "6" => "php",
                "18" => "C++",
                "3" => "python"
               );
uksort($names, "languages");
print_r ($names);
?>

Bottom Line

The uksort() function in PHP is an essential tool that allows us to sort the arrays according to keys. The uksort() function accepts the two parameters and returns the sorted array on the successful execution. This function provides the flexibility to maintain the key-value association and customize the callback function according to needs.

About the author

Zainab Rehman

I'm an author by profession. My interest in the internet world motivates me to write for Linux Hint and I'm here to share my knowledge with others.