1

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?

1
  • 1
    $data is not the array index Commented Jan 12, 2014 at 20:04

3 Answers 3

6

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

Sign up to request clarification or add additional context in comments.

Comments

2

Try

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

 $unixdate = strtotime($date);

 if ($unixdate < time()) {

 unset($array[$key]);

 }

}

print_r($array);

2 Comments

Looks like it is working! But it is removing today (1/12/14) too. Probably an issue with the if statement, but any thoughts as to why?
@ErikBerger Use strtotime('today') instead of time() for your comparison (from koala_dev's answer)
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.