Functions to sort arrays in PhP
Hi all,
Today I will list down the most common functions used to sort arrays in PhP. Hope this helps to keep in touch with various functions needed to sort your array related assignments.
| functions | what does this mean? |
|---|---|
| array_multisort() | Sort multi dimensional arrays |
| arsort() | sort an array in reverse order and maintain index association |
| asort() | Sorts an array and have index association |
| ksort | Sorts an array by key |
| krsort | Sort an array by its keys in reverse order |
| rsort() | Sort an array in reverse order |
| Shuffle() | Shuffles an array |
| uksort() | Sort an array by keys by using a user defined comparison function |
| usort() | Sort an array by values by using a user defined comparison function |
[<?php
$names=array(“d”=>”Arun”,”e”=>”Bimal”,”f”=>”Chris”);
asort($names);
foreach($names as $key=>$value){
echo “$key=$value </br >”;
}
?>]
The above scripts will sort the arrays in the alphabetical order and will show out put as
d=Arun
e=Bimal
f=Chris
On the other hand, if we use ARSORT(), we can reverse the list according to the values. Try the following.
[<?php
$names=array(“d”=>”Arun”,”e”=>”Bimal”,”f”=>”Chris”);
arsort($names);
foreach($names as $key=>$value){
echo “$key=$value </br >”;
}
?>]
The output will be:
f=Chris
e=Bimal
d=Arun
Now lets sort the array by key.
[<?php
$names=array(“d”=>”Kristopher”,”e”=>”Larry”,”f”=>”Micheal”);
ksort($names);
print_r ($names);
?>]
Here we use “KSORT() to sort the values by its indices. Lets see the output.
Array ( [d] => Kristopher [e] => Larry [f] => Micheal )
Now we can reverse this order by using KRSORT() and the new output will be:
Array (
[f] => Micheal
[e] => Larry
[d] => Kristopher )
SHUFFLE()
This function helps to shuffle the contents of an array.
[<?php
$num = array(1,2,3,4,5);
Shuffle($num);
foreach($num as $key=>$value){
echo “$key=$value <br />”;}
?>]
The output will show the keys and its values:
0=4
1=2
2=1
3=5
4=3
Everytime you refresh the browser, the values for each of the arrays will change.
Thats all for today… I will publish more functions related to use of array later.
Thanks for reading..
Surej