How to use uasort in PHP
In this article, I will explain how the uasort() function can be used in PHP.
uasort() function in PHP
- The uasort() function is used to sort an array by a user-made comparison function.
- The uasort() function does not assigns new keys for the elements.
- The uasort() function is useful for sorting with custom algorithms.
- The uasort() function maintains the existing key index.
- The uasort() function returns TRUE on success, or FALSE on failure.
Syntax
Parameter
- array array is required parameter. the specified array to be sort.
-
function function is required parameter. the function must return -1, 0, or 1 for this method to work correctly. It should be written to accept two parameters to compare.
- If a = b, return 0
- If a > b, return 1
- If a < b, return -1
Example
The following example show to how the uasort() function can be used in PHP.
<html>
<body>
<h3 style="color: royalblue;">uasort() function example in PHP</h3>
<?php
function my_sort($x, $y)
{
if ($x == $y) return 0;
return ($x > $y) ? -1 : 1;
}
$language = array("10" => "ASP.NET".'<br/>',
"20" => "PHP".'<br/>', "60" => "C#".'<br/>',
"40" => "SqlServer".'<br/>');
uasort($language, "my_sort");
print_r ($language);
?>
</body>
</html>
|
Output
You may also want to read these related articles here
Got a programming related question? You may want to post your question here