w3resource

PHP: uasort() function

PHP: Maintaining index association, sort an array with a user-defined comparison function

The uasort() function is used to sort an array by its values using a user-defined comparison function.
The function maintains the existing key index.

Version:

(PHP 4 and above)

Syntax:

uasort(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 supplied function. Required
-

Return value:

TRUE on success or FALSE on failure.

Value Type: Boolean.

Example :

<?php
function my_sort($x, $y)
{
if ($x == $y) return 0;
return ($x > $y) ? -1 : 1;
}
$people = array("10" => "javascript",
"20" => "php", "60" => "vbscript",
"40" => "jsp");
uasort($people, "my_sort");
print_r ($people);
?>

Output:

Array ( [60] => vbscript [20] => php [40] => jsp [10] => javascript )

Pictorial Presentation:

php function reference: uasort() function

View the example in the browser

Practice here online :

See also

PHP Function Reference

Previous: sort
Next: uksort



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/php/function-reference/uasort.php