PHP Tutorials - How to Sort Arrays in PHP, Different Sorting Methods in PHP


How to Sort Arrays in PHP, Different Sorting Methods in PHP


The Sorting is a technique to ordering an array's element by ascending or descending order.The PHP provides the number of sort functions to do this. The sort() function sorts the array based on the values in it in ascending order, The rsort() function does exactly the same thing but it sorts the array in descending order. The ksort() and krsort() sorts array by the associated key
The following examples shows the each sort function with example.


Regular Sorting

<?php
$Colors = array("Red", "Pink","Greeen",
"Blue","Yellow" ) ;
echo "<strong>Before sorting the array is</strong><br/>";
foreach ($Colors as $color) {
echo $color . "<br/>";
}
sort ($Colors) ;
echo "<strong>After Sorting the array is</strong> <br/>";
foreach ($Colors as $color) {
echo $color . "<br/>";
}

?>

output
Before sorting the array is
Red
Pink
Greeen
Blue
Yellow
After Sorting the array is 
Blue
Greeen
Pink
Red
Yellow 


Reverse Sorting

$Colors = array("Red", "Pink","Greeen",
"Blue","Yellow" ) ;
echo "<string>Before sorting the array is</strong><br/>";

foreach ($Colors as $color) {
echo $color . "<br/>";
}

rsort ($Colors) ;
echo "<strong>After Sorting the array is</strong> <br/>";
foreach ($Colors as $color) {
echo $color . "<br/>";
}

output
Before sorting the array is
Red
Pink
Greeen
Blue
Yellow
After Sorting the array is 
Yellow
Red
Pink
Greeen
Blue





Sorting with Keys in ascending order


$Colors = array("open"=>"PHP", "Microsoft"=>"ASP","Sun"=>"Java",
"IBM"=>"DB2","oracle"=>"oracle" ) ;
echo "<string>Before sorting the array is</strong><br/>";

foreach ($Colors as $color) {
echo $color . "<br/>";
}

rsort ($Colors) ;
echo "<strong>After Sorting the array is</strong> <br/>";
foreach ($Colors as $color) {
echo $color . "<br/>";
}
output
Before sorting the array is
PHP
ASP
Java
DB2
oracle
After Sorting the array is 
DB2
ASP
Java
PHP
oracle


Sorting with Keys in descending order

$Colors = array("open"=>"PHP", "Microsoft"=>"ASP","Sun"=>"Java",
"IBM"=>"DB2","oracle"=>"oracle" ) ;
echo "<string>Before sorting the array is</strong><br/>";

foreach ($Colors as $color) {
echo $color . "<br/>";
}

krsort ($Colors) ;
echo "<strong>After Sorting the array is</strong> <br/>";
foreach ($Colors as $color) {
echo $color . "<br/>";
}
output
Before sorting the array is
PHP
ASP
Java
DB2
oracle
After Sorting the array is 
oracle
PHP
Java
ASP
DB2




{ 0 comments... read them below or add one }

Post a Comment