CODING ACADEMY

View Original

How to Sort Arrays in PHP

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:

See this content in the original post

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:

See this content in the original post

HOW TO SORT PHP ARRAYS IN DESCENDING ORDER

We use the rsort() function as follows:

See this content in the original post

The output looks like this:

See this content in the original post

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

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

See this content in the original post

The output looks like this:

See this content in the original post

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

We use the ksort() function:

See this content in the original post

The output looks like this:

See this content in the original post

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

We use the arsort() function:

See this content in the original post

The output looks like this:

See this content in the original post

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

We use the krsort() function:

See this content in the original post

The output looks like this:

See this content in the original post