PHP uksort | Sort Associative Array By Key Using Callback

PHP uksort is an inbuilt Function in PHP. It sorts an associative array by key using a user-defined callback function. It is very useful if we want to sort an array in a custom manner. However, unlike usort, this function preserves the original keys of the array. In this article, we will discuss the PHP uksort Function.

Note: This function is most helpful in sorting Associative Arrays because it preserves the relation between keys and values.

Syntax

boolean uksort( $array, ‘function_name’);

Parameters

The PHP uksort Function expects two mandatory parameters. The description of the parameters is as follows:

  • $array: The first parameter is the array you want to sort.
  • function_name: The second parameter is the name of the function you want to use to sort the array. The comparison function should return an integer value. If both the elements are equal, it should returns 0. If the first parameter is greater than the second, it should return 1 and otherwise -1.

Caution: If you return non integer values from the comparison function, they will be cast to integer values. Hence, values such as 0.9 or 0.1 will both cast to integer value 0.

Return Value

The PHP uksort Function returns a boolean (true/false). However, it sorts the original input array. Also, it preserves the association between keys and values.

Examples

Let’s discuss a few examples of using the PHP uksort.

Example 1: Simple Comparison Function

For instance, consider an integer array and a simple comparison function.

<?php
	function compare($a, $b) {
		if ($a == $b) {
			return 0;
		} else if ($a > $b) {
			return 1;
		} else {
			return -1;
		}
	}

	$testArray = array(1 => 4, 0 => 2, 3 => 1, 2 => 5, 4 => 3);
	uksort($testArray, 'compare');
	/*
	Array
	(
	    [0] => 2
	    [1] => 4
	    [2] => 5
	    [3] => 1
	    [4] => 3
	)
	*/
?>

In the above example, the comparison function will return an integer value according to the parameters. The function sorts the arrays according to the keys. Also, you can note that it preserves the original keys of the input array.

Example 2: Associative Array

Similarly, you can sort an associative array on keys using the uksort function. In the below example, we sort the array containing strings using PHP strcmp Function.

<?php
	function compare($a, $b) {
		return strcmp($a, $b);
	}

	$testArray = array('a' => 'apple', 'c' => 'cat', 'd' => 'dog', 'b' => 'ball');
	uksort($testArray, 'compare');print_r($testArray);
	/*
	Array
	(
	    [a] => apple
	    [b] => ball
	    [c] => cat
	    [d] => dog
	)
	*/
?>

Conclusion

In this article, we discussed the PHP uksort Function. It sorts an array according a user-defined function. You can read more about it on PHP Official Documentation. Also, read more about PHP Array Functions on Concatly.

Spread the Knowledge

Leave a Reply

Your email address will not be published. Required fields are marked *