PHP asort() & arsort()


asort(array [,sort_flags]) sorts an associative array in ascend order by values.

<?PHP
	$arr=array("1"=>"Carbon","2"=>"carbon","3"=>"Protein", "4"=>"fat",);
    asort($arr, SORT_STRING);
	foreach($arr as $key=>$val) echo "$key, $val; "; 
    //1, Carbon; 3, Protein; 2, carbon; 4, fat;
?>

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.
<?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; "; 
    //1, Carbon; 2, carbon; 4, fat; 3, Protein; 
?>

arsort() sorts an associative array in descend order by values.
<?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; "; 
	//3, Protein; 4, fat; 2, carbon; 1, Carbon; 
?>