Link to home
Start Free TrialLog in
Avatar of tmbdesign
tmbdesign

asked on

PHP remove expired date from array

Hello,
I have an array of dates.  

$dates="02/07/09,02/28/09,03/07/09,03/28/09";

I am trying to display three dates from array:

$date1 = $dates[0];
$date2 = $dates[1];
$date3 = $dates[2];

What's the best way to go about only displaying upcoming dates and not displaying dates that have passed.

Thanks in advance.
Avatar of Zoppo
Zoppo
Flag of Germany image

Hi tmbdesign,

you can try somthing like this:

> $str="02/07/09,02/28/09,03/07/09,03/28/09";
> $dates = explode( ",", $str );
> $date_now = date_create();
> foreach( $dates as $date )
> {
>  if ( date_create( $date ) > $date_now )
>  {
>   echo $date . "<br>\n";
>  }
> }

Output is:

> 02/28/09
> 03/07/09
> 03/28/09

Hope that helps,

ZOPPO
Avatar of tmbdesign
tmbdesign

ASKER

Thanks for the response ZAPPO!

I need to get each if the dates into its own variable.  How would I change your code to accomplish this?

Thanks
ASKER CERTIFIED SOLUTION
Avatar of Zoppo
Zoppo
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
As a practical matter, all your date-related code will work better if you use ISO8601-format dates.  In PHP, this is date('c') - YYYY-MM-DDTHH:MM:SS

And your code will be more reliable and easier to write if you use strtotime() and date() together.

i will post an example for this problem in a moment, ~Ray

<?php // RAY_expired_dates.php
error_reporting(E_ALL);
echo "<pre>"; // READABILITY
 
// TEST DATA WITH AN ERROR DELIBERATELY INSERTED
$dates="02/07/09,02/28/09,03/07/09,FOO,03/28/09";
 
// MAKE THE TEST DATA INTO AN ARRAY
$date_array = explode(',', $dates);
 
// CONVERT TO A SUBSET OF ISO8601
$iso_date_array = array();
foreach ($date_array as $ptr => $date_thing)
{
   if (!$ts = strtotime($date_thing))
   {
      echo "BOGUS DATE IN $date_thing AT OFFSET $ptr \n";
      continue;
   } else {
      $iso_date_array[] = date('Y-m-d', $ts);
   }
}
 
// VISUALIZE THE DATA
var_dump($iso_date_array);
 
 
// GET TODAY
$today = date('Y-m-d');
echo "TODAY: $today \n \n";
 
// SHOW DATES THAT ARE IN THE PAST
foreach ($iso_date_array as $iso_date_thing)
{
   if ("$iso_date_thing" <  "$today") echo "PAST: $iso_date_thing\n";
   if ("$iso_date_thing" == "$today") echo "TODAY: $iso_date_thing \n";
   if ("$iso_date_thing" >  "$today") echo "FUTURE: $iso_date_thing \n";
}

Open in new window

Not a problem at all for my application!

Works great.

Thanks Zoppo!!
Good advice.

Thanks for the tip Ray.