Amit Dhamu

Writes Code

Sorting an Array in PHP

If our PHP array looks like this:

$f1_drivers = array(
 '1' => array('forename'=>'Lewis', 'surname'=>'Hamilton', 'team'=>'McLaren'),
    '2' => array('forename'=>'Jenson', 'surname'=>'Button', 'team'=>'McLaren'),
 '3' => array('forename'=>'Fernando', 'surname'=>'Alonso', 'team'=>'Ferrari'),
   '4' => array('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, $subkey) {
  return strnatcmp($a['surname'], $subkey['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.


array sorting / php / strnatcmp / usort

← Google Analytics Tracking Code Copyright Trick →