Loop between Two Dates in PHP

There are times that you want to loop between two dates in PHP. If you have, for example, formatted the date like m/d/Y, you cannot simply use it in while loop statement.

Before you can loop between two dates in PHP, you need to convert it first to Unix timestamp using the strtotime function.

Here’s an example of how to do it:

  1. $startDate = strtotime($checkin);
  2. $endDate = strtotime($checkout);
  3.  
  4. while ($startDate < $endDate) {
  5.         $startDate = strtotime('+1 day', $startDate);
  6.        
  7.         //add other code here
  8. }

The example above is useful in many ways. Like for example, if you want to get the special price of rooms in a Hotel.

Say in November 15 – 16 the price per room is different. Take a look at the following record:

id room_id date_from date_to price 1 1 3200.00 5 1 7/8/2012 7/9/2012 3000.00 7 1 10/14/2012 10/27/2012 3100.00 4 1 11/15/2012 11/16/2012 4000.00

As you can see, a room have special price. So, in order to get the price based on the date a guest would like to reserved, you need to loop between the checkin and checkout date.

Comments

If one would have a look at the dates... they're very significant indeed! The room price intensifies the contiguous coincidences... I just hope it's not only me... :) Thanks sir!

i am from Italy hello. Can you help me translate? /rardor

hi guys :). I am looking for help for me and my girl. i am from France

hi guys :). I am looking for help for me and my girl. i am from France

Add new comment