I have the following code that return's the next 13 Mondays from today's date.
for($i=1; $i<=13; $i++){
echo date("Y-m-d", strtotime('+'.$i.' Monday'))."<br>";
}
I want to be able to amend this so it not only shows the next 13 Mondays but the Monday that has just past.
I tried amending the code as follows but I then get two instances of the next Monday returned.
for($i=-1; $i<=13; $i++){
echo date("Y-m-d", strtotime('+'.$i.' Monday'))."<br>";
}
Data returned.
2015-04-13
2015-04-20 //<--
2015-04-20
2015-04-27
2015-05-04
2015-05-11
2015-05-18
2015-05-25
2015-06-01
2015-06-08
2015-06-15
2015-06-22
2015-06-29
2015-07-06
2015-07-13
Any ideas on how I achieve this?
I would do it like this:
for($i =- 1; $i <= 13; $i == 0 ? $i += 2 : $i++){
echo date("Y-m-d", strtotime("$i Monday")) . "<br>";
}
Using a ternary operator to check if $i
is 0 - and if, increase it by 2 instead of 1 :)
Try this:
echo date("Y-m-d", strtotime('-1 Monday'))."<br>";
for($i=1; $i<=13; $i++){
echo date("Y-m-d", strtotime('+'.$i.' Monday'))."<br>";
}
Or you need only one for
statement?
You can use this:
for($i=-1; $i<=13; $i++){
if($i !== 0){
echo date("Y-m-d", strtotime('+'.$i.' Monday'))."<br>";
}
}
You just have to omit the case that $i is zero.
function mondays() {
$begin = new DateTime('last monday');
$end = clone $begin;
$end->add(new DateInterval('P14W')); // next 13 + last
$interval = new DateInterval('P1W');
$daterange = new DatePeriod($begin, $interval ,$end);
foreach($daterange as $date){
yield $date;
}
}
foreach(mondays() as $date){
echo $date->format("Y-m-d"), PHP_EOL;
}
This should works (and you can test also other days != today)
//In order to avoid problems with midnight and daylight saving time
$refTime = date("Y-m-d 12:00:00");
for($i=-1; $i<13; $i++){
echo date("Y-m-d", strtotime("$refTime this Monday +".$i*7 ." days"))."<br>";
}
My approach will be the following (by using DateTime class)
$monday = new DateTime('last monday'); //if today is monday this will return last week's
$oneWeek = new DateInterval('P1W');
for($i=0; $i<=13; $i++){
echo $monday->format('Y-m-d')."<br>";
$monday->add($oneWeek);
}