Looping through a date range with PHP

Josh Sherman
1 min read
Software Development PHP

Looping through a date range isn’t as simple as looping through an array with foreach but it doesn’t take much additional code to get the job done. To loop through a date range you will need to use a loop (I prefer a while loop) and increment the date by using strtotime. I’ll convert the timestamp back to a human readable date as well just because I prefer to work with data I can read (because I’m a human and all ;)

$date = '2014-08-01'

while ($date <= '2014-08-31')
{
	echo $date . "\n";

	$date = date('Y-m-d', strtotime($date . ' +1 day'));
}

Not much to it! The conversion back to Y-m-d is just my personal preference. You can easily omit that and use UNIX timestamps instead if you’d like.

Join the Conversation

Good stuff? Want more?

Weekly emails about technology, development, and sometimes sauerkraut.

100% Fresh, Grade A Content, Never Spam.

Related Articles