PHP Array User Defined Comparison

What is uasort() Function?

Explanation

The "uasort()" function sorts an array with a user defined comparison function and maintain index association.

Syntax:


uasort(array,sorttypefunction)

In the above syntax "array" is the array to be sorted,with a user defined comparison function.The user defined function should return 0,1,-1.

Example :


<?php
function my_sort($a, $b)
{
if ($a == $b) return 0;
return ($a > $b) ? -1 : 1;
}
$p = array("Swanson" => "Joe",
"Griffin" => "Peter", "Quagmire" => "Glenn",
"swanson" => "joe", "griffin" => "peter",
"quagmire" => "glenn");
uasort($p, "my_sort");
print_r ($p);
?>
Result :

Array
(
[griffin] => peter
[swanson] => joe
[quagmire] => glenn
[Griffin] => Peter
[Swanson] => Joe
[Quagmire] => Glenn
)

In the above example the array "$p" is sorted, using the user defined function and displays the values.

PHP Topics


Ask Questions

Ask Question