Home >>PHP Array Functions >PHP uksort() Function

PHP uksort() Function

PHP uksort() Function

PHP uksort() function is used to sort the given input array according to its keys and not to the values using a user-defined comparison function. It accepts two parameters $array and the user-defined function name. It returns a boolean value TRUE on success and FALSE on failure as result.

Syntax:

uksort($array, function);

Parameter Values

Parameter Description
array This is a required parameter. It defines the array to sort.
function This is an optional parameter. It defines the callable comparison function.

Here is an example of uksort() function in PHP:

<html>
<body>
<?php
function compare($a,$b)
{
if ($a==$b) return 0;
  return ($a<$b)?-1:1;
}
$arr=array("a"=>1,"b"=>2,"c"=>10,"d"=>66,"e"=>5);
uksort($arr,"compare");
foreach($arr as $x=>$value)
   {
   echo "Key =" . $x . ", Value =" . $value;
   echo "<br>";
   }
?>
</body>
</html>
Output:
Key =a, Value =1
Key =b, Value =2
Key =c, Value =10
Key =d, Value =66
Key =e, Value =5

Example 2:

<html>
<body>
<pre>
<?php
function compare($a,$b)
{
if ($a==$b) return 0;
  return ($a<$b)?-1:1;
}
$arr=array("a"=>1,"b"=>2,"c"=>10,"d"=>66,"e"=>5,"f"=>25,"g"=>31);
uksort($arr,"compare");
print_r($arr);
?>
</pre>
</body>
</html>
Output:
Array
(
    [a] => 1
    [b] => 2
    [c] => 10
    [d] => 66
    [e] => 5
    [f] => 25
    [g] => 31
)

No Sidebar ads