Home > Articles > Data > MySQL

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Sorting Arrays Alphabetically

sort($a, SORT_NUMERIC);
sort($a, SORT_STRING);
<pre>
<?php
  $a = array('4', 31, '222', 1345);
  sort($a, SORT_NUMERIC);
  print_r($a);
  sort($a, SORT_STRING);
  print_r($a);
?>
</pre>

Sorting an Array (sort.php)

Numeric arrays can be sorted rather easily by using sort(). However, a problem exists if the array contains both numeric and string values (for instance, "2" > "10" but 2 < 10). Therefore, the sorting can be tweaked so that a special data type is used for comparing elements when sorting:

  • SORT_NUMERIC sorts elements as numbers.
  • SORT_REGULAR sorts elements according to their data type (standard behavior).
  • SORT_STRING sorts elements as strings.

Here is the output of the preceding listing:

Array
(
    [0] => 4
    [1] => 31
    [2] => 222
    [3] => 1345
)
Array
(
    [0] => 1345
    [1] => 222
    [2] => 31
    [3] => 4
)
  • + Share This
  • 🔖 Save To Your Account