Sorting By Functions in PHP

Sometimes we’ll want to sort a collection by something other than its natural order. For example, suppose we wanted to sort strings by their length instead of alphabetically. Here’s an example of custom sorts in PHP.

<?php

// We implement a comparison function for string lengths.
function lenCmp($a, $b) {
    return strlen($a) <=> strlen($b);
}

$fruits = ["peach", "banana", "kiwi"];

// Now we can use usort with this custom comparison function 
// to sort $fruits by name length.
usort($fruits, 'lenCmp');
print_r($fruits);

// We can use the same technique to sort an array of 
// objects that aren't built-in types.
class Person {
    public $name;
    public $age;

    public function __construct($name, $age) {
        $this->name = $name;
        $this->age = $age;
    }
}

$people = [
    new Person("Jax", 37),
    new Person("TJ", 25),
    new Person("Alex", 72)
];

// Sort $people by age using usort.
usort($people, function($a, $b) {
    return $a->age <=> $b->age;
});

print_r($people);

In this PHP version, we use the usort function to sort arrays with a custom comparison function. The <=> operator (spaceship operator) is used for comparison, which is similar to the cmp.Compare function in the original example.

For sorting objects, we define a Person class and create an array of Person objects. We then use an anonymous function to compare the age property of the objects.

When you run this script, you should see output similar to:

Array
(
    [0] => kiwi
    [1] => peach
    [2] => banana
)
Array
(
    [0] => Person Object
        (
            [name] => TJ
            [age] => 25
        )
    [1] => Person Object
        (
            [name] => Jax
            [age] => 37
        )
    [2] => Person Object
        (
            [name] => Alex
            [age] => 72
        )
)

This demonstrates how to implement custom sorting in PHP, both for simple arrays and for arrays of objects.