|
|
PHP Array User Defined Values Comparison
|
Tutorials » Php »
|
Topic |
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 => $v\n";
}
?>
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.
|
|
A Note |
Learn PHP programming language tutorial with simple and neat example. Hope you enjoy this free tutorial.
Do give us your valuable feedback and suggestions on this online tutorial. This is a Copyright Content.
|
|
|
|