Home > DeveloperSection > Blogs > Sorting of an array in PHP

Sorting of an array in PHP


PHP PHP  Array  Sorting 
Ratings:
1 Comment(s)
 286  View(s)
Rate this:

Sorting of an array in PHP


In PHP there are some sorting function .These function are used to sort the array.

sort() :

 

This function is used to sort in ascending alphabetical order.

<?php

$mobile = array("Samsung", "Nokia", "Micromax");

sort($mobile);

$length = count($mobile);

for($a = 0; $a < $length; $a++) {

    echo $mobile[$a];

    echo "<br>";

}

?>

 

Output:

Micromax
Nokia
Samsung

 

rsort():

This function is used to sort in descending alphabetical order.

<?php

$mobile = array("Samsung", "Nokia", "Micromax");

rsort($mobile);

$length = count($mobile);

for($a = 0; $a < $length; $a++) {

    echo $mobile[$a];

    echo "<br>";

}

?>

 

Output:

Samsung
Nokia
Micromax

 

asort():

Sort an associative array in ascending order, according to the value.

<?php

$salary = array("Neha"=>"35000", "Shikha"=>"45000", "Ravi"=>"40000");

asort($salary);

 

foreach($salary as $a => $a_value) {

    echo "Key=" . $a . ", Value=" . $a_value;

    echo "<br>";

}

?>

 

Output:

Key=Neha, Value=35000
Key=Ravi, Value=40000
Key=Shikha, Value=45000

 

ksort():

Sort an associative array in ascending order, according to the key.

<?php

$salary = array("Shikha"=>"45000", "Neha"=>"35000", "Ravi"=>"40000");

ksort($salary);

 

foreach($salary as $a => $a_value) {

    echo "Key=" . $a . ", Value=" . $a_value;

    echo "<br>";

}

?>

 

Output:

Key=Neha, Value=35000
Key=Ravi, Value=40000
Key=Shikha, Value=45000

 

arsort():

Sort an associative array in descending order, according to the key.

<?php

$salary = array("Shikha"=>"45000", "Neha"=>"35000", "Ravi"=>"40000");

arsort($salary);

 

foreach($salary as $a => $a_value) {

    echo "Key=" . $a . ", Value=" . $a_value;

    echo "<br>";

}

?>

 

Output:

Key=Shikha, Value=45000
Key=Ravi, Value=40000
Key=Neha, Value=35000

 

krsort():

Sort an associative array in descending order, according to the key.

<?php

$salary = array("Shikha"=>"45000", "Neha"=>"35000", "Ravi"=>"40000");

krsort($salary);

 

foreach($salary as $a => $a_value) {

    echo "Key=" . $a . ", Value=" . $a_value;

    echo "<br>";

}

?>

 

Output:

Key=Shikha, Value=45000
Key=Ravi, Value=40000
Key=Neha, Value=35000

 


Nice information

By Simond Gear on   one month ago

Hi zack your explanation is very well about sorting of an array in PHP. 


Don't want to miss updates? Please click the below button!

Follow MindStick