Thursday, 25 September 2014

uasort in PHP

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

Syntax:

uasort(array,function)
 
Parameters Description: 
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" );
uasort($people,"mysort");
print_r($people);
?>

O/P:

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

0 comments:

Post a Comment