Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I find the maximum and minimum date in an array?

I need to find the maximum and minimum date from a given array using PHP.

I have $date_arr which contains following values,

  $date_arr = array('0'=>'20-05-2015','1'=>'02-01-2015','2'=>'30-03-2015');

Here, I need to get the larger date as '20-05-2015' and the minimum date as '02-01-2015'.

How can I achieve this?

like image 972
soniya soniya Avatar asked Feb 24 '15 05:02

soniya soniya


2 Answers

<?php

$date_arr=array(0=>'20-05-2015',1=>'02-01-2015',2=>'30-03-2015');

usort($date_arr, function($a, $b) {
    $dateTimestamp1 = strtotime($a);
    $dateTimestamp2 = strtotime($b);

    return $dateTimestamp1 < $dateTimestamp2 ? -1: 1;
});

echo 'Min: ' . $date_arr[0];
echo '<br/>';
echo 'Max: ' . $date_arr[count($date_arr) - 1];


?>
like image 138
Adrian Cid Almaguer Avatar answered Sep 30 '22 05:09

Adrian Cid Almaguer


max() and min() works fine with your array:

echo "Latest Date: ". max($dates)."\n";
echo "Earliest Date: ". min($dates)."\n";
like image 44
Azima Avatar answered Sep 30 '22 07:09

Azima