PHP Array Sorting

PHP Array Sorting

The values contained in the array can be sorted, for numeric values are sorted from lowest to highest value while for the string will be ranked from a to z. To sort the values used sort() function with the terms of the array elements are integers, for the array with string element can be used asort() function.

Example :
Write the following code.
 

<?
$x=array(3,4,7,8,5,2,1,6,0,9);
echo("Before sorting  : ");
for($i=0;$i<count($x);$i++)
{
 echo("$x[$i],");
}

sort($x);
echo("<BR>After Sorting : ");
for($i=0;$i<count($x);$i++)
{
 echo("$x[$i],");
}

$s=array(f,j,b,d,e,i,a,c,g,h);
echo("<P>Before Sorting : ");
for($i=0;$i<count($x);$i++)
{
 echo("$s[$i],");
}

sort($s);
echo("<BR>After Sorting : ");
for($i=0;$i<count($s);$i++)
{
 echo("$s[$i],");
}
$country=array("us"=>"United States","jp"=>"Japan","ca"=>"Canada");
echo("<P>Before Sorting : ");
for($i=1;$i<=count($country);$i++)
{
 list($act,$val)=each($country);
  echo("<BR>Element number-$i is $act and the value is $val");
}
asort($country);
echo("<P>After Sorting : ");
for($i=1;$i<=count($country);$i++)
{
 list($act,$val)=each($country);
  echo("<BR>Element number-$i is $act and the value is $val");
}
?>

PHP Array Sorting

0 comments:

Post a Comment