basically it should sort from A to Z then by numeric order, but using mixed type the function do not know how to sort the array and give a random result...
in the manual page there is a huge warning says that:
Be careful when sorting arrays with mixed types values because sort()
can produce unpredictable results.
you can add a parameter to the function:
SORT_REGULAR - compare items normally (don't change types)
SORT_NUMERIC - compare items numerically
SORT_STRING - compare items as strings
SORT_LOCALE_STRING - compare items as strings, based on the current locale. Added in PHP 4.4.0 and 5.0.2, it uses the system locale, which can be changed using setlocale().
According to manual here on php.net
Edit 1:
Probably you can obtain the best sort result using the flag SORT_REGULAR because it does not change the variable type and numbers remain numbers and strings remain strings but it will also give you a strange result
fruits[0] = 121
fruits[1] = Lemon
fruits[2] = apple
fruits[3] = banana
fruits[4] = lemon
fruits[5] = 20
fruits[6] = 40
fruits[7] = 50
I think because it compare the ascii code from the letters of strings and L is before a b l...
121 is in first place because you wrote it like a string "121"
Edit 2:
The best way to proceed is to separate the types: (this way php will treat "121" as a number and not a string, but you can simply decide it by the if clause)
<?php
$fruits = array("lemon","Lemon", 20, "banana", "apple","121",40,50);
$arr1=array();
$arr2=array();
foreach($fruits as $key=>$val){
if (is_numeric($val))
array_push($arr1,$val);
else
array_push($arr2,$val);
}
sort($arr1,SORT_NUMERIC);
sort($arr2,SORT_LOCALE_STRING);
$fruits = array_merge($arr1,$arr2);
echo "<pre>";
foreach ($fruits as $key => $val) {
echo "fruits[" . $key . "] = " . $val . "\n";
}
?>