I have an array of dates formatted in 'm/d/Y' (month/day/year):

$array = array(

'1/10/2014',
'1/11/2014',
'1/12/2014',
'1/13/2014',
'1/14/2014'
);

and I'd like to output the array with only dates of today or in the future. So if today is 1/12/2014 it would eliminate the 1/10/2014 and 1/11/2014.

Here is what I have that isn't working:

foreach ($array as $date) {

 $unixdate = strtotime($date);

 if ($unixdate < time()) {

 unset($array[$date]);

 }

}

print_r($array);

I guess I'm not using unset correctly because it prints the entire array?

有帮助吗?

解决方案

I suggest you look into array_filter(). Also you want to use today's date at 12:00:00 for the comparisson, not the current time.

$array = array(
    '1/10/2014',
    '1/11/2014',
    '1/12/2014',
    '1/13/2014',
    '1/14/2014'
);

$array = array_filter($array,function($date){
    return strtotime($date) >= strtotime('today');
});

print_r($array); //Array ( [2] => 1/12/2014 [3] => 1/13/2014 [4] => 1/14/2014 )

*Note: PHP 5.3 needed for anonymous functions

其他提示

Try

foreach ($array as $key => $date) {

 $unixdate = strtotime($date);

 if ($unixdate < time()) {

 unset($array[$key]);

 }

}

print_r($array);

foreach ($array as &$date) Hi using call by reference and $date = NULL; in the loop

OR

foreach ($array AS $key => $date) {

 $unixdate = strtotime($date);

 if ($unixdate < time()) {

    unset($array[$key]);

 }

}

if you want to completely remove those entries

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top