PHP uksort() Function

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

TRUE on success. FALSE on failure

Tip: Use the uasort() function to sort an array by values using a user-defined comparison function.

Parameter Description
array Required. Specifies the array to sort
myfunction Optional. A string that define a callable comparison function. The comparison function must return an integer <, =, or > than 0 if the first argument is <, =, or > than the second argument

Syntax

uksort(array,myfunction);

Example

function my_sort($a,$b)
{
if ($a==$b) return 0;
  return ($a<$b)?-1:1;
}

$array=array("d"=>3,"b"=>2,"c"=>7,"a"=>"5");
uksort($array,"my_sort");
 
foreach($array as $x=>$x_value)
{
   echo "Key=" . $x . ", Value=" . $x_value;
   echo "
";
}

Output

Key=a, Value=5
Key=b, Value=2
Key=c, Value=7
Key=d, Value=3

Leave a Reply

Your email address will not be published. Required fields are marked *