Prateek Anand
Prateek Anand

Reputation: 39

Getting wrong result after sorting datetime array in PHP

I want to sort an array by datetime in decending order. Here is the example array:

<?php
$var1 = "2016-12-30 12:30:59";
$var2 = "2015-11-21 11:30:59";
$var3 = "2017-01-15 10:30:59";

$a = array($var1, $var2, $var3);

function compare_func($a, $b) {
    // CONVERT $a AND $b to DATE AND TIME using strtotime() function
    $t1 = strtotime($a[0]);
    $t2 = strtotime($a[1]);

    return ($t2 - $t1);
}

usort($a, "compare_func");

var_export($a);
?>

The output I am getting is:

array (
  0 => '2017-01-15 10:30:59',
  1 => '2015-11-21 11:30:59',
  2 => '2016-12-30 12:30:59',
)

Upvotes: 0

Views: 53

Answers (2)

NID
NID

Reputation: 3294

Try this:

<?php
$var1 = "2016-12-30 12:30:59";
$var2 = "2015-11-21 11:30:59";
$var3 = "2017-01-15 10:30:59";

$arr = array($var1, $var2, $var3);

function date_sort($a, $b) {
    return strtotime($b) - strtotime($a);
}
usort($arr, "date_sort");
print_r($arr)


?>

OUTPUT in decending order

Array
(
    [0] => 2017-01-15 10:30:59
    [1] => 2016-12-30 12:30:59
    [2] => 2015-11-21 11:30:59
)

Upvotes: 0

LF-DevJourney
LF-DevJourney

Reputation: 28554

You can compare the string directly.

function compare_func($a, $b) {
    return ($a > $b);
}

Upvotes: 2

Related Questions