Users Pricing

blog

home / developersection / blogs / sorting of an array in php

Sorting of an array in PHP

zack mathews 2123 06 Jun 2016 Updated 15 Mar 2018

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


 


zack mathews

Other


1 Comments