What is Array short() function in php?
Sorting the array by using key as well as value.
Sort by value :- php provide many functions to sort an array. We can sort an array by value, key or randomly.
sort() :- sort function is used to sort the array in ascending order.
asort() :- Sorts an array and also maintain the index position.
rsort() :- it sort an array in reverse order.
arsort() :- this function will sort an array in reverse order and maintain index association like asort + rsot + sort = arsort( )
natsort() :- sorts an array using natural order. Means it sorts alphanemeric string in such a way that human sorts the key/value associations.
natcasesort() :-
Sort() Funtion Example.
File Name:- index.php
<?php
$num = array(1,6,50, 5, 2, 60, 55);
print_r($num);
sort($num);
echo "
";
print_r ($num);
?>
Output :-
Output :-
Array ( [0] => 1 [1] => 6 [2] => 50 [3] => 5 [4] => 2 [5] => 60 [6] => 55 ) Array ( [0] => 1 [1] => 2 [2] => 5 [3] => 6 [4] => 50 [5] => 55 [6] => 60 )
Sort() Funtion Example.
File Name:- index.php
<?php $flowers = array("rose", "daisy" , "orchid", "tulip", "camomile");
sort($flowers);
for ($i=0; $i <= 4; $i++) //prints the array elements
echo $flowers[$i];
?>
Output :-
camomile
daisy
orchid
rose
tulip
Example.
File Name:- index.php
<?php
$num = array("mahtab","alam","zeba","kalam","bebs");
print_r($num);
sort($num);
echo "
after sorting value :
";
print_r ($num);
?>
Output :-
Array ( [0] => mahtab [1] => alam [2] => zeba [3] => kalam [4] => bebs )
after sorting value :Array ( [0] => alam [1] => bebs [2] => kalam [3] => mahtab [4] => zeba )
Example. asort()
File Name:- index.php
<?php
$name = array("m"=>"mahtab","a"=>"alam","b"=>"bebs");
print_r($name);
asort($name);
echo "
after sorting value :";
print_r ($name);
?>
Output :-
Output :- Array ( [m] => mahtab [a] => alam [b] => bebs )
after sorting value :Array ( [a] => alam [b] => bebs [m] => mahtab )
Example. rsort()
File Name:- index.php
<?php
$name = array("m"=>"mahtab","a"=>"alam","b"=>"bebs");
print_r($name);
rsort($name);
echo "
after sorting value :";
print_r ($name);
?>
Output :-
Output :-
Array ( [m] => mahtab [a] => alam [b] => bebs )
after sorting value :Array ( [0] => mahtab [1] => bebs [2] => alam )
Example. natsort()
File Name:- index.php
<?php
$name1 = $name2 = array("emp01","emp50","emp20","emp5");
sort($name1);
print_r($name1);
natsort($name2);
print_r($name2);
?>
Output :-
Sort array by key.
ksort() :- this function sorts an array by key maintaining the correction with the value. This function is useful for associative array.
krsort() :- sort an array by key in reverse order maintaing the correlation with the value. This is useful for associative array.
Example. ksort()
File Name:- index.php
<?php
$ar = array(30=>"raj",10=>"mahtab",50=>"alka", 2=>"kalam");
ksort($ar);
print_r($ar);
?>
Output :-
Array ( [2] => kalam [10] => mahtab [30] => raj [50] => alka )
Previous
Next