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

后端 未结 4 2070
情深已故
情深已故 2021-01-05 08:45

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\'         


        
相关标签:
4条回答
  • 2021-01-05 08:45

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

    echo "Latest Date: ". max($dates)."\n";
    echo "Earliest Date: ". min($dates)."\n";
    
    0 讨论(0)
  • 2021-01-05 08:57
    $date_arr=array(0=>'2015-05-20',1=>'2015-02-21',2=>'2015-04-13',3=>'2020-04-30',4=>'2020-04-13');
    
    $max_date=$date_arr[0];
    for($i=0;$i<count($date_arr);$i++)
    {
        echo $date_arr[$i]. ' ,';
        if( $max_date < $date_arr[$i+1])
        {
            $max_date=$date_arr[$i+1];
        }
    }  
    echo " Max= ". $max_date;
    
    0 讨论(0)
  • 2021-01-05 08:58
    <?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];
    
    
    ?>
    
    0 讨论(0)
  • 2021-01-05 09:11

    please Try this

    $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 讨论(0)
提交回复
热议问题