PHP:Sorting an Array

From Progzoo
Jump to navigation Jump to search

You can sort an array in PHP with sort

Sort an array

The function sort can be used if the sort is simple:

Sort the list 2,7,5,4.

[Font] [Default] [Show] [Resize] [History] [Profile]

Sort an array in reverse

We use the function rsort:

Sort the list 2,7,5,4 in reverse.

[Font] [Default] [Show] [Resize] [History] [Profile]

Sort an array using a custom comparator

You can create your own comparator. This mens that you decide how the sort is to be done. It is a function that returns a negative, zero or a positive integer depending on how the first argument (let's call $o1) compares to the second argument (let's call $o2).

return -1 (or any negative number) if $o1 comes before $o2
return  0 if $o1 and $o2 are the same
return  1 (or any positive number) if $o1 comes after $o2

[Font] [Default] [Show] [Resize] [History] [Profile]