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

Sorting of an array in PHP


PHP PHP  Array  Sorting 
Ratings:
0 Comment(s)
 182  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

 


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

Follow MindStick