Thursday, 25 September 2014

uksort in PHP

PHP uksort() function is utilized to sort an array by element keys user-defined function.
Function returns TRUE on success, or FALSE on failure.

Syntax:

uksort(array,function)
array : Required. Specifies the array to sort
function : Required. A user specified function. The function must return -1, 0, or 1 for this method to work correctly.
                 It should be written to accept two parameters to compare, and it should work something like this:

  • If a = b, return 0
  • If a > b, return 1
  • If a < b, return -1

Example:

<?php
function mysort($a, $b)
{
if($a == $b) return 0;
return ($a > $b) ? -1 : 1;
}
$people = array( "Swanson"=>"Joe","Griffin"=>"Peter","Quagmire"=>"Glenn",
"swanson"=>"joe","griffin"=>"peter","quagmire"=>"glenn" );
uksort($people,"mysort");
print_r($people);
?>

O/P:

Array ( 
        [swanson] => joe 
        [quagmire] => glenn 
        [griffin] => peter 
        [Swanson] => Joe 
        [Quagmire] => Glenn
        [Griffin] => Peter 
       )

0 comments:

Post a Comment