Check out Scrivo

Do you want to try out Scrivo? Then here's a demo for you that does not just get your feet wet but lets you plunge right in.

Contact us

For more information, please contact us. We're happy to help you out!

Next Sep 30 Previous

Item 547241

You want to sort an array of dates in ascending order:


$dates = array(
        new DateTime("2012-01-01"),
        new DateTime("2011-01-01"),
        new DateTime("2013-01-01")

usort($dates, function($a, $b) { ... });


What goes at the dots.

A: return $a < $b;
B: return $a->diff($b);
C: return $a->compare($b);
D: return $a->getOffset($b);
E: None of these


Sorry folks, the correct answer is E. Let's look a litte closer at the answer options.

Answer A is not correct, the usort() sort function has to return less than zero if the first argument ($a) needs to come before the second argument ($b) in the results, more than zero if it should placed after the second and zero if the are equal. You can compare DateTime objects this way but it will result in true or false ( or 1), not the correct result for a sort function and the sort results will be undetermined. To propery sort the array you could use return $a==$b?0($a<$b?-1:1); if you are desparete to sqeeze it all on one line.

The sort function has to return an integer, DateTime::diff() returns some fancy DateInterval object, so answer B is not going to work either. If you insist on using it amaze your friends and try return ($a->diff($b)->invert?1:-1)*$a->diff($b)->days;.

Answer C looks good but unfortunately there is no DateTime::compare() method. And the method DateTime::getOffset() exists but it returns the timezone offset so answer D is not correct too.