Sunday, December 3, 2017

anil

How To Sort An Array in PHP ?

Mostly web developers face the problem of sorting an array in PHP. So to save their time here I am sharing the solution with example.


Feel free to join us and you are always welcome to share your thoughts that our readers may find helpful.

There are 6 functions to sort an array in PHP -

#1. sort() - Sort Array in Ascending Order

Below example shows sorted array in ascending order 
<?php
$name = array('sonia','monica','raj','yogita');
sort($name); print_r($name); ?>

Output :- 

Array
(
    [0] => monica
    [1] => raj
    [2] => sonia
    [3] => yogita
)

#2. rsort() - Sort Array in Descending Order

Below example shows sorted array in descending order 
<?php
$name = array('sonia','monica','raj','yogita');
rsort($name); print_r($name); ?>

Output :- 

Array
(
    [0] => yogita
    [1] => sonia
    [2] => raj
    [3] => monica
)

#3. asort() - Sort Array (Ascending Order), According to Value

Below example shows sorted array in ascending order, according to value

<?php
$code = array('sonia'=>'98','monica'=>'12','raj'=>'112','yogita'=>'10');
asort($code); print_r($code); ?>

Output :- 

Array
(
    [yogita] => 10
    [monica] => 12
    [sonia] => 98
    [raj] => 112
)

#4. ksort() - Sort Array (Ascending Order), According to Key

Below example shows sorted array in ascending order , according to key..

<?php
$code = array('sonia'=>'98','monica'=>'12','raj'=>'112','yogita'=>'10');
ksort($code); print_r($code); ?>

Output :- 

Array
(
    [monica] => 12
    [raj] => 112
    [sonia] => 98
    [yogita] => 10
)

#5. arsort() - Sort Array (Descending Order), According to Value

Below example shows sorted array in descending order, according to value

<?php
$code = array('sonia'=>'98','monica'=>'12','raj'=>'112','yogita'=>'10');
arsort($code); print_r($code); ?>

Output :- 

Array
(
    [raj] => 112
    [sonia] => 98
    [monica] => 12
    [yogita] => 10
)

#6. krsort() - Sort Array (Descending Order), According to Key

Below example shows sorted array in descending order , according to key..

<?php
$code = array('sonia'=>'98','monica'=>'12','raj'=>'112','yogita'=>'10');
krsort($code); print_r($code); ?>

Output :- 

Array
(
    [yogita] => 10
    [sonia] => 98
    [raj] => 112
    [monica] => 12
)

Using the above functions you can easily sort an array. 


About Author -

Hi, I am Anil.

Welcome to my eponymous blog! I am passionate about web programming. Here you will find a huge information on web development, web design, PHP, Python, Digital Marketing and Latest technology.

Subscribe to this Blog via Email :

Note: Only a member of this blog may post a comment.