Sort a multidimensional array by date element in PHP

Sorting a multidimensional array by element containing date. Use the usort() function to sort the array. The usort() function is PHP builtin function that sorts a given array using user-defined comparison function. This function assigns new integral keys starting from zero to array elements.

Syntax:

boolean usort( $array, "function_name")

Parameters: This function accepts two parameters as shown in the above syntax and are described below:

  • $array: This parameter specifies the array which u want to sort.
  • function_name: This parameter specifies the name of a user-defined function which compares the values and sort the array specified by the parameter $array. This function returns an integer value based on the following conditions. If two argument are equal then it returns 0, If first argument is greater than second, it returns 1 and if first argument is smaller than second, it returns -1.

Return Value: This function returns Boolean type value. It returns TRUE in case of success and FALSE in case of failure.

We use strtotime to convert given time string to a timestamp object. Once we have timestamps, we subtract them to decide greater.

Program:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
  
// Declare a multidimensional array
// and initialize it
$array = Array (
    Array (
        "gfg" => "GFG_1",
        "datetime" => "2019-02-22 11:29:45",
        ),
    Array (
        "gfg" => "GFG_2",
        "datetime" => "2019-02-13 11:29:45",
    ),
    Array (
        "gfg" => "GFG_3",
        "datetime" => "2019-02-15 11:29:45",
    )
);
  
// Comparision function
function date_compare($element1, $element2) {
    $datetime1 = strtotime($element1['datetime']);
    $datetime2 = strtotime($element2['datetime']);
    return $datetime1 - $datetime2;
  
// Sort the array 
usort($array, 'date_compare');
  
// Print the array
print_r($array)
  
?>

chevron_right


Output:

Array
(
    [0] => Array
        (
            [gfg] => GFG_2
            [datetime] => 2019-02-13 11:29:45
        )

    [1] => Array
        (
            [gfg] => GFG_3
            [datetime] => 2019-02-15 11:29:45
        )

    [2] => Array
        (
            [gfg] => GFG_1
            [datetime] => 2019-02-22 11:29:45
        )

)


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.