medianicwebdesign

How to Sort Arrays in PHP

It is always easier to grab a specific piece of information from sorted data, otherwise you have to go through each element of the array one at a time. For example, lets say you have stored the score of different students in a class in an array or a table. If the data is not sorted by the scores obtained, you will have to look at the score of each student in the class before you can tell who obtained the highest and lowest score. If the table was already sorted low to high on basis of scores, just looking at the score of first student would tell you the lowest mark.

Sorting makes a lot of tasks that require accessing or obtaining a specific set of data very easy and efficient. In this tutorial, we will learn how to use built-in PHP functions to sort different kinds of array.

Sorting an Array by Value

Sorting an array by the value of its elements is very easy in PHP. You can choose to maintain or discard key-value associations, and you can also define your own functions to dictate how elements are sorted. I’ll show you how in this section of the tutorial.

You can use the sort(&$array, $sort_flags) function to sort the values of an array from low to high. However, it will not maintain any key-value associations when sorting the array. New keys are assigned to sorted elements instead of a simple reordering. The optional second parameter allows you to specify how the elements should be sorted. It can have six different values:

  1. SORT_REGULAR—This will sort the values without changing their types.
  2. SORT_NUMERIC—This will sort the values by comparing them numerically.
  3. SORT_STRING—This will sort the values by comparing them as strings.
  4. SORT_LOCALE_STRING—This will compare the values as string based on the current locale. You can update the locale yourself by using setlocale().
  5. SORT_NATURAL—This will sort the items using “natural ordering” while comparing them as strings.
  6. SORT_FLAG_CASE—This can be combined with SORT_STRING or SORT_NATURAL to turn off case-sensitivity while sorting strings.

Here are a couple of sorting examples to help you quickly grasp the difference between all the sort flags.

Powered by WPeMatico

Leave a Comment

Scroll to Top