PHP usort | Sort By Value Using User-Defined Function

PHP usort is an inbuilt Function in PHP. It sorts an array by value using a user-defined callback function. It is very useful if we want to sort an array in a custom manner. However, the function assigns new keys to the elements present after sorting. In this article, we will discuss the PHP usort Function. Also, we will discuss a few examples of using it.

Syntax

boolean usort( $array, ‘function_name’);

Parameters

The PHP usort 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 usort Function returns a boolean (true/false). However, it sorts the original input array.

Examples

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

Example 1: Simple Comparison Function

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

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

	$testArray = array(4, 2, 1, 5, 3);
	usort($testArray, 'compare');
?>

In the above example, the comparison function will return an integer value according the parameters. Therefore, the array after sorting will look like this:

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)

Example 2: Sort Multi-Dimensional Array

Similarly, you can sort a multi-dimensional array using PHP usort Function. In the below example, we sort the array containing strings using PHP strcmp Function.

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

	$testArray[]['test'] = 'aa';
	$testArray[]['test'] = 'aaaaa';
	$testArray[]['test'] = 'a';
	usort($testArray, 'compare');
	
	/*
	testArray[0]['test'] = a
	testArray[1]['test'] = aa
	testArray[2]['test'] = aaaaa
	*/
?>

Example 3: Calling Method of an Object

Likewise, we can also make the comparison function a method of a class. You can call the comparison method by passing the object and method name in an array. You can read more about classes on Object Oriented Programming Concepts in PHP on Concatly.

<?php
	class Compare {
		public function compareItems($a, $b) {
			return $a <=> $b; //spaceship operator
		}
	}

	$testArray = array(2, 4, 1, 3, 5);
	$compare = new Compare();
        //Pass the object of the class and method name
	usort($testArray, array($compare, 'compareItems'));
	print_r($testArray);
	/*
	Array
	(
	    [0] => 1
	    [1] => 2
	    [2] => 3
	    [3] => 4
	    [4] => 5
	)
	*/
?>

Also, we make use of the Spaceship Operator in PHP. It is available only after PHP 7.0.

Example 4: Using Lambda Function

Also, you can pass a lambda or anonymous function instead of defining a function separately. We will discuss about Anonymous Functions in a later article.

<?php

	$testArray = array(4, 2, 1, 5, 3);
	usort($testArray, function($a, $b) {
		if ($a == $b) {
			return 0;
		} else if ($a > $b) {
			return 1;
		} else {
			return -1;
		}
	});
	print_r($testArray);
	/*
	Array
	(
	    [0] => 1
	    [1] => 2
	    [2] => 3
	    [3] => 4
	    [4] => 5
	)
	*/
?>

Conclusion

In this article, we discussed the PHP usort 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 *