w3resource

PHP: usort() function

PHP: Sort an array by values using a user-defined comparison function

The usort() function is used to sort an array by its values using a user-defined comparison function. If the array you wish to sort needs to be sorted by some non-trivial criteria, you should use this function.
The function removes any existing keys and assigns new keys for the elements in the array.

Version:

(PHP 4 and above)

Syntax:

usort(array_name, user-defined-function)

Parameters:

Name Description Required /
Optional
Type
array_name The specified array which will be sorted. Required Array
user-defined-function User define function. Required
-

Return value:

TRUE on success, or FALSE on failure.

Value Type: Boolean.

Example:

<?php
function user_compare($x, $y)
{
if ($x == $y)
return 0;
else if ($x > $y)
return 1;
else
return -1;
}
$array1 = array(22,33,66,55,11);
usort($array1, 'user_compare');
foreach($array1 as $key => $value)
{
echo "$key: $value\n";
}
?>

Sample Output:

0: 11  1: 22  2: 33  3: 55  4: 66 

Pictorial Presentation:

php function reference: usort() function

View the example in the browser

Practice here online:

See also

PHP Function Reference

Previous: uksort
Next: Calendar Functions cal_days_in_month



PHP: Tips of the Day

PHP: Check whether a request is GET or POST

Better use $_SERVER['REQUEST_METHOD']:

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    //...
}

Ref : https://bit.ly/3kw5mRk