PHP Usort Function With Examples

The PHP usort is a built-in PHP function that sorts an array with the use of a user-defined comparison function.

In this article, we will talk about usort PHP function in a detailed explanation as well as example programs that could be helpful to your future projects. This topic is a continuation of the previous topic, entitled PHP array_filter function.

What is PHP usort?

In PHP, usort is a built-in function in PHP which can sort a given array by the use of a function name a user-defined comparison.

Further, this function is quite useful in terms of sorting an array in a new manner. Also, this function will assign new keys which start from zero to the present elements of an array and those existing keys will be lost.

Syntax

usort(array, myfunction)

Parameter values

ParameterDescription
arrayThis parameter is required and it specifies an array that you want to be sorted.
myfunctionThis parameter is optional and specifies the name of the user-defined function that compares each value and sorts the array which has been specified by the parameter.

Further, this parameter returns a value of an integer which is based on the following conditions. Once the two arguments are equal, it means that they will return true and 0 value. Then if the first argument is greater than the second value it will return 1, and last if the first argument is smaller than the second number it will return a value of -1.

Example

<?php

	// PHP program to illustrate usort() function

	// This is the user-defined function used to compare
	// values to sort the input array
	function comparatorFunc( $num1, $num2)
	{
		// If $x is equal to $y it returns 0
		if ($num1== $num2)
			return 0;
	
		// if x is less than y then it returns -1
		// else it returns 1	
		if ($num1 < $num2)
			return -1;
		else
			return 1;
	}
	
	// Input array
	$arrays= array(3, 10, 2, 4, 6);

	usort($arrays, "comparatorFunc");
	
	print_r($arrays);

?>

Output

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

More PHP usort example programs

The following program could help you understand PHP usort in the easiest and better way.

1. Example program using usort function to sort an array of strings by length

The example program below is use a usort() function to sort the given name by length

Example

<?php

$programmerNames = [ 'Glenn', 'Jude',  'Adones' ];
usort($programmerNames, fn($x,$y) => strlen($x) <=> strlen($y));

var_dump($programmerNames);

2. Example program using usort() function to sort an array with object elements.

The example program below uses a usort() function to sort an array with object elements.

Example

<?php

class Laptops
{
    public $brands;
    public $price;

    public function __construct(string $brands, int $price)
    {
        $this->brands = $brands;
        $this->price = $price;
    }
}

$group = [
    new Laptops('Acer', 340),
    new Laptops('Dell', 425),
    new Laptops('Asus', 130),
];

usort($group, fn($x, $y) => $x->price <=> $y->price);

print_r($group);

Output

Array
(
    [0] => Laptops Object
        (
            [brands] => Asus
            [price] => 130
        )

    [1] => Laptops Object
        (
            [brands] => Acer
            [price] => 340
        )

    [2] => Laptops Object
        (
            [brands] => Dell
            [price] => 425
        )

)

What does usort return?

The boolean usort array will return a boolean a true or false to indicate when it was successful or not and the argument array function will pass as a reference.

Summary

In summary, you have learned about PHP usort. This article also discussed what is PHP usort, and what usort returns.

I hope this lesson has helped you learn a lot. Check out my previous and latest articles for more life-changing tutorials which could help you a lot.

Leave a Comment