PHP asort() & arsort()
asort(array [,sort_flags]) sorts an associative array in ascend order by values.
1
2
3
4
5
6
<?PHP
$arr=array("1"=>"Carbon","2"=>"carbon","3"=>"Protein", "4"=>"fat",);
asort($arr, SORT_STRING);
foreach($arr as $key=>$val) echo "$key, $val; ";
?>
The sort can be modified by sort_flags which include:
• SORT_REGULAR: sort normally
• SORT_NUMERIC: sort numerically
• SORT_STRING: sort as strings
• SORT_LOCALE_STRING: sort as strings based on the current locale
• SORT_NATURAL: sort as strings using "natural ordering"
• SORT_FLAG_CASE: combined with SORT_STRING or SORT_NATURAL to sort case insensitively
Sort by string and case insensitive.
1
2
3
4
5
6
<?PHP
$arr=array("1"=>"Carbon","2"=>"carbon","3"=>"Protein", "4"=>"fat",);
asort($arr, SORT_STRING | SORT_FLAG_CASE);
foreach($arr as $key=>$val) echo "$key, $val; ";
?>
arsort() sorts an associative array in descend order by values.
1
2
3
4
5
6
<?PHP
$arr=array("1"=>"Carbon","2"=>"carbon","3"=>"Protein", "4"=>"fat",);
arsort($arr, SORT_STRING | SORT_FLAG_CASE);
foreach($arr as $key=>$val) echo "$key, $val; ";
?>