LEARN TO CODE

View Original

How to Sort Associative Arrays in PHP

In this lesson I will show you how to sort associative arrays in PHP.

The 4 functions we will use are:

  • asort()

  • ksort()

  • arsort()

  • krsort()

Consider the following associative array containing names and ages. 

See this content in the original post

The name is known as the key and the age is known as the value in the key/value pair.

ksort()

We use ksort() to sort the array by the key in ascending order as follows:

See this content in the original post

The output will be:

See this content in the original post

asort()

We use asort() to sort the array by the value in ascending order as follows:

See this content in the original post

The output will be:

See this content in the original post

krsort()

We use krsort() to sort the array by the key in descending order as follows:

See this content in the original post

The output will be:

See this content in the original post

arsort()

We use arsort() to sort the array by the value in descending order as follows:

See this content in the original post

The output will be:

See this content in the original post

If you would like to learn more about PHP then enrol in the PHP for Beginners course now.