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?
To find the first Monday, subtract one from the start date (to cover for starting on Monday). Then find the next Monday.
On average, there is a Friday the 13th once every 212.35 days. Friday the 13ths occurs with an average frequency of 1.7218 per year or about 3477 since the year 1 CE.
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?
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With