Reputation: 10704
I have a PHP script which records things based on the day. So it will have a weekly set of inputs you would enter.
I get the data correctly, but when i do $day ++;
it will increment the day, going passed the end of the month without ticking the month.
example:
//12/29
//12/30
//12/31
//12/32
//12/33
Where it should look like
//12/29
//12/30
//12/31
//01/01
//01/02
My script is as follows:
$week = date ("Y-m-d", strtotime("last sunday"));
$day = $week;
$run = array(7); //this is actually defined in the data posted to the script, which is pretty much just getting the value of the array index for the query string.
foreach( $run as $key=>$value)
{
$num = $key + 1;
$items[] = "($num, $user, $value, 'run', '$day')";
echo "".$day;
$day ++;
}
Should I be manipulating the datetime differently for day incrementations?
Upvotes: 1
Views: 91
Reputation: 269
To increase time you should use strtotime("+1 day");
here is simple example of using it
<?php
$now_time = time();
for($i=1;$i<8;$i++) {
$now_time = strtotime("+1 day", $now_time);
echo date("Y-m-d", $now_time) . "<br>";
}
?>
Upvotes: 0
Reputation: 120644
You refer to $day
as a "datetime" but it is just a string - that is what date()
returns. So when you do $day++
you are adding 1
to "2015-12-02"
. PHP will do everything it can to make "2015-12-02"
into a number and then add 1
to it, which is not date math. Here is a simple example:
<?php
$name = "Fallenreaper1";
$name++;
echo $name
?>
This will output:
Fallenreaper2
This is how I would do it, using an appropriate data type (DateTime
):
<?php
$day = new DateTime('last sunday');
$run = array(7);
foreach ($run as $key => $value) {
$num = $key + 1;
$dayStr = $day->format('Y-m-d');
$items[] = "($num, $user, $value, 'run', '$dayStr')";
echo $dayStr;
$day->modify('+1 day');
}
Upvotes: 2
Reputation: 28121
You can use
$day = date("Y-m-d", strtotime($day . " +1 day"));
instead of
$day++;
Upvotes: 3