I am trying to create an array starting with today and going back the last 30 days with PHP and I am having trouble. I can estimate but I don’t know a good way of doing it and taking into account the number of days in the previous month etc. Does anyone have a good solution? I can’t get close but I need to make sure it is 100% accurate.
+7
A:
Try this:
<?php
$d = array();
for($i = 0; $i < 30; $i++)
$d[] = date("d", strtotime('-'. $i .' days'));
?>
Terw
2008-12-03 16:36:15
I think you meant for the date to be assigned to $d[i], not $d[].
Matt
2008-12-03 19:08:26
Matt: No $d[] is better.
OIS
2008-12-04 12:13:25
A:
You can use time to control the days:
for ($i = 0; $i < 30; i++)
{
$timestamp = time();
$tm = 86400 * $i; // 60 * 60 * 24 = 86400 = 1 day in seconds
$tm = $timestamp - $tm;
$the_date = date("m/d/Y", $tm);
}
Now, within the for loop you can use the $the_date variable for whatever purposes you might want to. :-)
Pedrin
2008-12-03 16:36:22
Pedrin, watch out for this method using time. I used to do this, then noticed that it won't calculate correctly at certain times involving day-light savings time.Instead, I would advise using the strtotime function.-Matt
Matt
2008-12-03 19:06:53