This is a tutorial on how to loop / iterate through a period of dates in PHP. In this guide, we will loop through all of the dates that fall between our specified start date and end date.
Take a look at the PHP code snippet above:
<?php //The date that you want to start at. $start = '2010-01-01'; //The date that you want to stop at. $end = '2015-12-31'; //We set our counter to the start date. $currentDate = strtotime($start); //While the current timestamp is smaller or equal to //the timestamp of the end date. while($currentDate <= strtotime($end)){ //Format the timestamp and print it out //for illustrative purposes. $formatted = date("d-M-Y", $currentDate); echo $formatted, '<br>'; //Add one day onto the timestamp / counter. $currentDate = strtotime("+1 day", $currentDate); }
Explanation:
- We specified the date that we want to start at. In this case, it is 2010-01-01.
- We specified the end date. i.e. The date that we want our loop to stop at. You could set this to today’s date by using date(“Y-m-d”);
- Our $currentDate variable contains the UNIX timestamp of the date that we are currently looking at. This variable will obviously change as we iterate through our dates.
- The logic behind our while loop is pretty simple. We basically tell it not to stop until the timestamp is equal to the timestamp of our end date. If our $currentDate variable contains a timestamp that is greater than the timestamp of our end date, the loop will stop. Remember: A Unix timestamp will increase as time goes on, simply because it contains the number of seconds that have passed since the 1st of January 1970. i.e. Yesterday’s timestamp will be a smaller number than today’s timestamp.
- We print out a formatted version of the timestamp for example purposes. This is where you would carry out the logic of your application.
- We set the timestamp of our $currentDate variable to the next day.