How to 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 the following values,

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

Here I need to get a big date as '20 -05-2015 'and a minimum date as '02 -01-2015'.

How can i achieve this?

+4
source share
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];


?>
+6
source

Please, try

$date_arr = array('0' => '20-05-2015', '1' => '02-01-2015', '2' => '30-03-2015');
for ($i = 0; $i < count($date_arr); $i++)
{
    if ($i == 0)
    {
        $max_date = date('Y-m-d H:i:s', strtotime($date_arr[$i]));
        $min_date = date('Y-m-d H:i:s', strtotime($date_arr[$i]));
    }
    else if ($i != 0)
    {
        $new_date = date('Y-m-d H:i:s', strtotime($date_arr[$i]));
        if ($new_date > $max_date)
        {
            $max_date = $new_date;
        }
        else if ($new_date < $min_date)
        {
            $min_date = $new_date;
        }
    }
}
echo date('d-m-Y',strtotime($max_date));
echo date('d-m-Y',strtotime($min_date));
0
source

All Articles