Search code examples
phptimediscount

Script for dated discount


I'm a little new at PHP, so my script writing is still progressing. I have a page that users register for a seminar they have to pay for. If they register prior to 5 days before the seminar takes place, they get a discounted price, if they register post 5 days before the seminar takes place, they have to pay full price. I have written a PHP script that I think will do that (works is testing anyway) but I have a feeling there is a better way of writing it. I am just looking for any suggestions anyone has, if any. Your help is greatly appreciated. My script is as follows.

date_default_timezone_set('MST');
$discount_check  = date("YmdHis", mktime(date("H"), date("i"), date("s"), date("m") , date("d")+5 , date("Y") ));

//Made an array because there are several seminars a year and because I need to make it easy enough for others in my office (who don't know PHP) to add/edit seminar dates
$array = array(
'Utah_seminar' => '20120130153804',
'Seattle_seminar' => '20120723000000',
'Florida_seminar' => '20121005000000'
);

while ($seminar_dates = current($array)) 
{
    if ($discount_check >= $seminar_dates) 
    {
        echo 'discount is not eligible';
        break;
    }
    else
    {
        echo 'discount received';
        break;
    }
next($array);
}

Again, any help is greatly appreciated. Even if it's finding any hiccups with the code.


Solution

  • <?
    date_default_timezone_set('MST');
    
    $now = new DateTime();
    
    // Made an array because there are several seminars a year and because I need
    // to make it easy enough for others in my office (who don't know PHP) to
    // add/edit seminar dates
    $array = array(
        'Utah_seminar'    => new DateTime('2012-01-30 15:38:04'),
        'Seattle_seminar' => new DateTime('2012-07-23 00:00:00'),
        'Florida_seminar' => new DateTime('2012-10-05 00:00:00')
    );
    
    foreach ($array as $seminar => $date) {
        $cutoff = clone $date;
        $cutoff->modify('-5 days');
    
        if ($now > $cutoff) {
            echo "$seminar - discount is not eligible\n";
        } else {
            echo "$seminar - discount received\n";
        }
    }
    ?>