PHP Array User Defined Values Comparison

What is usort() Function?

Explanation

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

Syntax:


usort(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.Entire keys are assigned new.

Example :


<?php
function my_sort($a, $b)
{
if ($a == $b) return 0;
return ($a > $b) ? -1 : 1;
}
$fruit = array("1" => "Apple",
"2" => "Banana", "3" => "apple",
"4" => "banana");
usort($fruit, "my_sort");
while (list($k,$v)= each($fruit) )
{
echo "$k => $vn";
}
?>
Result :

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

In the above example the array "$fruit" is sorted based on values and assigned new keys, displays the values.

PHP Topics


Ask Questions

Ask Question