Приглашаем посетить
Добычин (dobychin.lit-info.ru)

Sorting Arrays Alphabetically

Previous
Table of Contents
Next

Sorting Arrays Alphabetically

sort($a, SORT_NUMERIC);
sort($a, SORT_STRING);


Numerical arrays can be sorted rather easily by using sort(). However, a problem exists if the array contains both numerical 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

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

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
)

NOTE

If you want to sort the elements of the array in reverse order, use rsort() (r for reverse). The same optional second parameters are allowed that can be used with sort().



Previous
Table of Contents
Next