PHP Sorting Arrays

The elements of an array can be sorted alphabetically or numerically in ascending or descending order.

PHP Functions For Sorting Arrays

In the previous chapter you’ve learnt the essentials of PHP arrays i.e. what arrays are, how to create them, how to view their structure, how to access their elements etc. You can do even more things with arrays like sorting the elements in any order you like.

PHP comes with a number of built-in functions designed specifically for sorting array elements in different ways like alphabetically or numerically in ascending or descending order. Here we’ll explore some of these functions most commonly used for sorting arrays.

  • sort() and rsort() — For sorting indexed arrays
  • asort() and arsort() — For sorting associative arrays by value
  • ksort() and krsort() — For sorting associative arrays by key

Sorting Indexed Arrays in Ascending Order : sort() function

The sort() function is used for sorting the elements of the indexed array in ascending order (alphabetically for letters and numerically for numbers).

The output will be as given bellow:

sorting

Sorting Indexed Arrays in Descending Order : rsort() function

The rsort() function is used for sorting the elements of the indexed array in descending order (alphabetically for letters and numerically for numbers).

Example:

The output will be:

reverse_array_php

Sorting Associative Arrays in Ascending Order By Value

The asort() function sorts the elements of an associative array in ascending order according to the value. It works just like sort(), but it preserves the association between keys and its values while sorting.

Example:

If you have any question relating the topic, you can ask it at our Forum Section.

 

Loading