PHP usort() function

PHP uksort() function
PHP cal_days_in_month() function

In this article, you will learn how to sort an array based on some user-defined function. The usort() function compares array elements by passing them to the user-defined function and sorts them according to the comparison result.

What is the syntax of the usort() function in PHP?

usort(array, myfunction)
ParameterDetails
arrayThe array to sort – Required
my_functionCallable function name (string).
The callable function compares two values and returns an integer <, =, or > 0 if the first value is <, = or > than second.
PHP usort() function

Examples of usort() function

Example 1. Sort the array elements using the user-defined function.

<?php
function my_function($x,$y)
{
if ($x==$y) return 0;
return ($x<$y)?-1:1;
}

$arr=array(3,15,21,9,86);
usort($arr,"my_function");
?>
PHP uksort() function
PHP cal_days_in_month() function

Stay up-to-date about PHP!

We don’t spam!

en English
X
Scroll to Top