d
Amit DhamuSoftware Engineer
 

Sorting an Array in PHP

4 minute read 00000 views

If our PHP array looks like this:

$f1_drivers = [
    1 => [
        'forename' => 'Lewis',
        'surname' => 'Hamilton',
        'team' => 'McLaren'
    ],
    2 => [
        'forename' => 'Jenson',
        'surname' => 'Button',
        'team' => 'McLaren'
    ],
    3 => [
        'forename' => 'Fernando',
        'surname' => 'Alonso',
        'team' => 'Ferrari'
    ],
    4 => [
        'forename' => 'Sebastian',
        'surname' => 'Vettel',
        'team' => 'Red Bull'
    ]
];

I want to sort my array by driver surname, so I have to create a little comparison function using a built-in PHP function called strnatcmp.

function sort_driver_surname($a, $b) {
    return strnatcmp($a['surname'], $b['surname']);
}

Finally, to execute the sort comparison function:

usort($f1_drivers, 'sort_driver_surname');

Now if I echo out the results of my array, I will get:

// Output of $f1_drivers
Array
(
    [0] => Array
        (
            [forename] => Fernando
            [surname] => Alonso
            [team] => Ferrari
        )

    [1] => Array
        (
            [forename] => Jenson
            [surname] => Button
            [team] => McLaren
        )

    [2] => Array
        (
            [forename] => Lewis
            [surname] => Hamilton
            [team] => McLaren
        )

    [3] => Array
        (
            [forename] => Sebastian
            [surname] => Vettel
            [team] => Red Bull
        )

)

This is not the most extensive example but should give you an idea on how to create sorting and comparison functions with your arrays.

You can find out more about sorting arrays at PHP.net.