PHP Array Sort: Learn in a simple way with multiple examples

Summary

In this post, you will learn the process of arranging data in a specific order. Here we will guide you through various methods to achieve this using multiple PHP array sort built-in functions like sort(), rsort() etc

Introduction

Sorting is to arrange data in a specific order. PHP offers various sorting methods, each tailored to different needs. The primary sorting functions include:

  • sort() : Sorts an array in ascending order.
  • rsort() : Sorts an array in descending order.
  • asort() : Sorts an associative array in ascending order, maintaining key-value associations.
  • arsort() : Sorts an associative array in descending order, maintaining key-value associations.
  • ksort() : Sorts an associative array by keys in ascending order.
  • krsort() : Sorts an associative array by keys in descending order.
  • usort() : Sorts an array using a user-defined comparison function.
  • uasort() : Sorts an associative array using a user-defined comparison function, maintaining key-value associations.
  • uksort() : Sorts an associative array by keys using a user-defined comparison function.

To further understand how each of these functions operates, let’s look at samples for each one.

Sorting Numeric Arrays

sort() and rsort()

The sort() function arranges an array in ascending order, while rsort() does the opposite, arranging it in descending order. Here’s how you can use them:

<?php
$numbers = [5, 3, 1, 4, 2];

// Sorting in ascending order
sort($numbers);

print_r($numbers);
?>

Result

Array(

    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5

)
<?php

// Sorting in descending order
rsort($numbers);
print_r($numbers);

?>

Result

Array(

    [0] => 5
    [1] => 4
    [2] => 3
    [3] => 2
    [4] => 1

)

Sorting Associative Arrays

Use functions like asort() and arsort() to retain associations when working with associative arrays, where each element contains a key-value pair.

asort() and arsort()

<?php

$fruits = [
    'apple' => 3,
    'banana' => 2,
    'cherry' => 5,
    'date' => 1
];

// Sorting in ascending order by values
asort($fruits);
print_r($fruits);

?>

Result

Array
(

    [date] => 1
    [banana] => 2
    [apple] => 3
    [cherry] => 5

)
<?php

$fruits = [
    'apple' => 3,
    'banana' => 2,
    'cherry' => 5,
    'date' => 1
];

// Sorting in descending order by values
arsort($fruits);
print_r($fruits);

?>

Result

Array
(

    [cherry] => 5
    [apple] => 3
    [banana] => 2
    [date] => 1

)

Sorting by Keys

It’s possible that you’ll need to occasionally sort an associative array just using its keys. This can be achieved by using the methods ksort() and krsort().

ksort() and krsort()

<?php

$colors = [
    'green' => 'forest',
    'red' => 'apple',
    'blue' => 'sky',
    'yellow' => 'banana'
];

// Sorting in ascending order by keys
ksort($colors);
print_r($colors);

?>

Result

Array
(

    [blue] => sky
    [green] => forest
    [red] => apple
    [yellow] => banana

)
<?php

$colors = [
    'green' => 'forest',
    'red' => 'apple',
    'blue' => 'sky',
    'yellow' => 'banana'
];

// Sorting in descending order by keys
krsort($colors);
print_r($colors);

?>

Result

Array
(

    [blue] => sky
    [green] => forest
    [red] => apple
    [yellow] => banana

)

Custom Sorting with usort()

In some cases, it may be necessary to sort an array using unique criteria that cannot be accommodated by the built-in sorting routines. In this situation, usort() is useful. You can create a unique comparison function with it.

Here’s an example where we sort an array of names based on the length of each name:

<?php

$names = ['John', 'Jane', 'Robert', 'Alice', 'Michael'];

// Custom comparison function
function compareNames($a, $b) {
    return strlen($a) - strlen($b);
}

// Sorting based on name length
usort($names, 'compareNames');
print_r($names);

?>

Result

Array
(

    [0] => Jane
    [1] => John
    [2] => Alice
    [3] => Robert
    [4] => Michael

)

Custom Sorting with uasort() and uksort()

In a manner similar to usort(), uasort() and uksort() enable you to custom sort associative arrays while preserving key-value associations. Here is a sample of how to order students in an associative array by their grades.

<?php

$students = [
    'Alice' => 85,
    'Bob' => 92,
    'Charlie' => 78,
    'David' => 95,
];

// Custom comparison function for uasort()
function compareScores($a, $b) {
    return $a - $b;
}

// Sorting by values (scores)
uasort($students, 'compareScores');
print_r($students);

?>

Result

Array
(

    [Charlie] => 78
    [Alice] => 85
    [Bob] => 92
    [David] => 95

)
<?php

$students = [
    'Alice' => 85,
    'Bob' => 92,
    'Charlie' => 78,
    'David' => 95,
];

// Custom comparison function for uksort()
function compareNames($a, $b) {
    return strcmp($a, $b);
}

// Sorting by keys (names)
uksort($students, 'compareNames');
print_r($students);

?>

Result

Array
(

    [Alice] => 85
    [Bob] => 92
    [Charlie] => 78
    [David] => 95

)

Sorting with Case Sensitivity

The PHP sorting functions are case-sensitive by default. This indicates that letters in uppercase will be sorted before those in lowercase. The SORT_NATURAL | SORT_FLAG_CASE options can be used in conjunction with the sorting algorithms to perform a case-insensitive sort

Here’s an example

<?php

$names = ['apple', 'Banana', 'cherry', 'Date'];

// Sorting in ascending order (case-insensitive)
sort($names, SORT_NATURAL | SORT_FLAG_CASE);

print_r($names);

?>

Result

Array
(

    [0] => apple
    [1] => Banana
    [2] => cherry
    [3] => Date

)
<?php
$names = ['apple', 'Banana', 'cherry', 'Date'];

// Sorting in descending order (case-insensitive)
rsort($names, SORT_NATURAL | SORT_FLAG_CASE);

print_r($names);

?>

Result

Array
(

    [0] => Date
    [1] => cherry
    [2] => Banana
    [3] => apple

)

As you can see, using the SORT_NATURAL | SORT_FLAG_CASE flags allows you to sort the array in a case-insensitive manner.

Sorting Multidimensional Arrays

Multidimensional arrays are a common tool used in practical applications. Such arrays need a little extra care when sorting since you have to indicate which subarray components to compare. Let’s use the following scenario to illustrate how to sort books by year when you have a collection of books with titles and publication years:

<?php

$books = [
    ['title' => 'PHP Basics', 'year' => 2019],
    ['title' => 'JavaScript Mastery', 'year' => 2020],
    ['title' => 'Python Fundamentals', 'year' => 2018],
    ['title' => 'Web Design Essentials', 'year' => 2021],
];

// Custom comparison function for sorting by year
function compareYears($a, $b) {
    return $a['year'] - $b['year'];
}

// Sorting the multidimensional array by year
usort($books, 'compareYears');
print_r($books);

?>

Result

Array
(
    [0] => Array
        (
            [title] => Python Fundamentals
            [year] => 2018
        )

    [1] => Array
        (
            [title] => PHP Basics
            [year] => 2019
        )

    [2] => Array
        (
            [title] => JavaScript Mastery
            [year] => 2020
        )

    [3] => Array
        (
            [title] => Web Design Essentials
            [year] => 2021
        )
)

Frequently Asked Questions

Q1. How does PHP sort work?

Ans: PHP array sort functions, like sort() and rsort(), use algorithms like quicksort or mergesort to rearrange array elements. Sorting can be done in ascending or descending order based on values. For keys, ksort() and krsort() sort alphabetically or in reverse. Custom sorting can be achieved using user-defined comparison functions.

Q2.How to sort array in PHP without using function?

Ans: To sort an array in PHP without using a built-in function, you can implement a simple sorting algorithm like bubble sort. Here’s an example of sorting an array in ascending order without using a function:

<?php
$myArray = array(5, 2, 9, 1, 5);
$length = count($myArray);
for ($i = 0; $i < $length - 1; $i++) {
    for ($j = 0; $j < $length - $i - 1; $j++) {
        if ($myArray[$j] > $myArray[$j + 1]) {
            $temp = $myArray[$j];
            $myArray[$j] = $myArray[$j + 1];
            $myArray[$j + 1] = $temp;
        }
    }
}
print_r($myArray);
?>

Q3.How to check if array is sorted in PHP?

Ans: To check if an array is sorted in PHP, you can iterate through the array and compare each element with the next one. If all elements are in non-decreasing (or non-increasing) order, the array is sorted. Use a loop and conditional statements to perform this check.

Conclusion

PHP array sort functions give you the power to arrange data as needed. Understanding these functions and their usage is essential for any PHP developer, as it enables you to create more organized and user-friendly web applications.

%d bloggers like this: