PHP Array User Defined Keys Comparison

What is uksort() Function?

Explanation

The "uksort()" function sorts an array by keys using a user-defined comparison function.

Syntax:


uksort(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;
}
$people = array("1" => "Apple",
"2" => "Banana", "3" => "apple",
"4" => "banana");
uksort($people, "my_sort");
while (list($k,$v)= each($people) )
{
echo "$k => $vn";
}
?>
Result :

4 => banana 3 => apple 2 => Banana 1 => Apple

In the above example the array "$people" is sorted in the descending order using the keys, displays the values.

PHP Topics


Ask Questions

Ask Question