var arr = [ "I", "learn", "JavaScript", "at", "work", 76 ];
arr = arr.sort(); // Store sorted array in original
alert( arr.join("\n") ); // Show one element per line - Click to run ->
Note: numbers are sorted before letters, and uppercase letters before lowercase ones.
function ciSort( e1, e2 ) {
// Convert to string to errorlessly handle other data types:
e1 = e1.toString().toLowerCase();
e2 = e2.toString().toLowerCase();
return e1>e2 ? 1 : ( e1<e2 ? -1 : 0 );
}
var arr = ["I","learn","the","JavaScript","LANGUAGE","intelligently",76];
arr = arr.sort(ciSort);
alert( arr.join("\n") );
Tip: you can also pass an anonymous function arr.sort( function() {...} ); for one-time uses.
$arr = array( 'I', 'learn', 'PHP' );
$successSorting = sort( $arr );
if( $successSorting )
print_r( $arr ); // Array ( [0] => I [1] => PHP [2] => learn )
else
echo 'Problem sorting this array!';
Sister method: reverse() modifies an array by inverting its order (first element becomes last, and vice-versa). Use sort() and then reverse() to display an array in reverse alphabetical order (descending order, Z to A, and then numbers) - reverse() handles storage order, not content.