PHP Programing language

array_usort(), array_uasort() and array_uksort() Function in PHP
Previous Home Next

array_usort()

The usort() function sorts an array using a user-defined comparison function.

Syntax:
usort(array,myfunction);

In above syntax, "array" specifies the array to sort and "myfunction" is 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

Example:

<?php
function my_sort($a,$b)
{
if ($a==$b) return 0;
   return ($a<$b)?-1:1;
}
$a=array(14,12,18,6);
usort($a,"my_sort");

$arrlength=count($a);
for($x=0;$x<$arrlength;$x++)
   {
   echo $a[$x];
   echo "<br>";
   }
?>  

Output:

6
12
14
18

array_uasort()

The uasort() function sorts an array by values using a user-defined comparison function.

Syntax:
uasort(array,myfunction);

In above syntax, "array" specifies the array to sort and "myfunction" is 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

Example:

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

$arr=array("a"=>14,"b"=>12,"c"=>18,"d"=>6);
uasort($arr,"my_sort");
  
foreach($arr as $x=>$x_value)
    {
    echo "Key=" . $x . ", Value=" . $x_value;
    echo "<br>";
    }

?>

 

Output:

Key=d, Value=6
Key=b, Value=12
Key=a, Value=14
Key=c, Value=18

array_uksort()

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

Syntax:
uksort(array,myfunction);

In above syntax, "array" specifies the array to sort and "myfunction" is 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

Example:

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

$arr=array("a"=>14,"b"=>12,"c"=>18,"d"=>6);
uksort($arr,"my_sort");
  
foreach($arr as $x=>$x_value)
    {
    echo "Key=" . $x . ", Value=" . $x_value;
    echo "<br>";
    }

?>

Output:

Key=a, Value=14
Key=b, Value=12
Key=c, Value=18
Key=d, Value=6

Previous Home Next

Tolal:0 Click:

Show All Comments

Did not find what you were looking for leave your name and message. We will revert within 24 hours
Name:
eMail:
Comment / Feedback: