0

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',
)

2 Answers 2

2

You can compare the string directly.

function compare_func($a, $b) {
    return ($a > $b);
}
Sign up to request clarification or add additional context in comments.

Comments

0

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
)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.