Thursday, 25 September 2014

usort in PHP

PHP usort() function is used to sort an array by its values using user-defined comparison function.
PHP usort() function removes if any existing keys and assigns new keys for the elements in the array.
Function returns TRUE on success, or FALSE on failure.

Syntax:

usort(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("Peter", "glenn", "Cleveland", "peter", "cleveland", "Glenn" );
usort($people,"mysort");
print_r($people);
?>

O/P:

Array ( 
          [0] => peter
          [1] => glenn 
          [2] => cleveland
          [3] => Peter
          [4] => Glenn
          [5] => Cleveland
         )

0 comments:

Post a Comment