Sorting Arrays in PHP

In this tutorial, we will explain to you about the sorting arrays in PHP. We will cover all the possible method provided by PHP with example.

Sorting Arrays in PHP, sort method, rsort method, asort method, arsort method, ksort method, krsort method, sort function, rsort function, asort function, arsort function, ksort function, krsort function, Array Sort in PHP, How to Sort Arrays in PHP, php array sort methods, PHP – sort array by array key, How to sort an array of associative arrays by value, php sort by key desc.

List of array sort methods

  1. sort()
  2. rsort()
  3. asort()
  4. arsort()
  5. ksort()
  6. krsort()

Method 1: sort()

sort() function used to sort an array in ascending order. In the example below, we create basic php array that holds the name of flowers and sorts them in alphabetical order using this method.

Here, another example for array with numbers and sorts in numerical order.

Method 2: rsort()

rsort() function used to sort an array in descending order. Let’s see with an example.

For array with numbers.

Method 3: asort()

asort() function used to sort associative array by their value in ascending order. Let’s take one example of a student’s mark.

Method 4: arsort()

arsort() function used to sorts associative array by their value in descending order. Let’s take the same example.

Method 5: ksort()

ksort() function used to sorts associative array by their key in ascending order. Let’s take the same example of student’s mark and it sorts the array by student’s name not by mark in ascending order.

Method 6: krsort()

krsort() function used to sort associative array by their key in descending order. See below example, it sorts the array by student’s name in descending order.

That’s it for today.
Thank you for reading. Happy Coding!

If you found value in this article,
you can support us by buying me a coffee! ☕

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *