How to Sort Associative Arrays in PHP

phplogo.jpg

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. 

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:

The output will be:

asort()

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

The output will be:

krsort()

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

The output will be:

arsort()

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

The output will be:

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