How to Sort Arrays in PHP

phplogo.jpg

In this lesson we look at how to sort arrays (including associative arrays) in PHP

HOW TO SORT PHP ARRAYS IN ASCENDING ORDER

We simply use the sort() function as follows:

Line 3: this array contains some names

Line 5: we sort the array called $names

Line 7: we echo a preformat tag so that the array is easy to read

Line 9: we print out the array

The output looks like this:

HOW TO SORT PHP ARRAYS IN DESCENDING ORDER

We use the rsort() function as follows:

The output looks like this:

HOW TO SORT A PHP ASSOCIATIVE ARRAY IN ASCENDING ORDER BY VALUE

Consider the following associative array and the asort() function:

The output looks like this:

HOW TO SORT A PHP ASSOCIATIVE ARRAY IN ASCENDING ORDER BY KEY

We use the ksort() function:

The output looks like this:

HOW TO SORT A PHP ASSOCIATIVE ARRAY IN DESCENDING ORDER BY VALUE

We use the arsort() function:

The output looks like this:

HOW TO SORT A PHP ASSOCIATIVE ARRAY IN DESCENDING ORDER BY KEY

We use the krsort() function:

The output looks like this: