PHP  Sorting Arrays

Values contained  in arrays can be sorted in different forms,either numerically or in alphabetical order.In numerical,they can be sort arrays in  ascending or descending.

Functions used in sort arrays

sort() function-  can be used in sorting  arrays in ascending order

rsort ()  function -can be used in sorting sort arrays in descending order

asort()  function – can be used in sorting associative arrays in ascending order according to the values they have

ksort()  function – can be used in sorting associative arrays in ascending order using keys

arsort()  function – can be used in sortingassociative arrays in descending order using the values assigned

krsort()  function – can be used in sorting associative arrays in descending order depending on the keys

Using sort() function  to Sort array in Ascending Order

Below example  sorts  $animals array in  ascending order according to alphabet

<?php
$animals = array("Sheep", "Goat", "Goat");
sort($animals);
?>

Below example sorts array marks in ascending order according to their numerical values.

<?php
$marks = array(14, 62, 24, 22, 11);
sort($marks);
?>

 Using  rsort()  to sort Array in Descending Order

Below example  sorts  $animals array in  descending order according to alphabet

<?php
$animals = array("Sheep", "Goat", "Goat");
rsort($animals);
?>

Below example sorts array marks in descending order according to their numerical values.

<?php
$marks = array(14, 62, 24, 22, 11);
rsort($marks);
?>

Using asort() to Sort Array in Ascending Order depending on their values

Below example sorts associative array in  ascending order according to the value.

<?php
$marks = array("Eric"=>"35", "Mellisa"=>"30", "Joe"=>"43");
asort($marks);
?>

Using ksort() to Sort Array in Ascending Order depending on their Keys

Below example sorts associative array in  ascending order according to the value.

<?php
$marks = array("Eric"=>"35", "Mellisa"=>"30", "Joe"=>"43");
ksort($marks);
?>

Using arsort()  to Sort Array Descending Order depending on their Value –

Below example sorts associative array in  descending order according to the value.

<?php
$marks = array("Eric"=>"35", "Mellisa"=>"30", "Joe"=>"43");
arsort($marks);
?>

 Using krsort() function to sort Array Descending Order Depending on their  Key

Below example sorts associative array in  descending order according to the value.

<?php
$marks = array("Eric"=>"35", "Mellisa"=>"30", "Joe"=>"43");
krsort($marks);
?>

 

About the Author: Eric K

My name is Eric.Am a software developer with skills in Php,Mysql, Java , Android,Node.js Above all, I have certification in Cisco Networking Associate (CCNA) and holds degree in Information Technology. Hire me: Email : kawi3462@gmail.com