Imran
Imran

Reputation: 37

How to get day names between to dates using for loop in php

I write following code to get results: -

$date_from = date('2018-12-14');
$date_from = strtotime($date_from);
$date_to = date('2018-12-16');
$date_to = strtotime($date_to);
for ($i=$date_from; $i<=$date_to; $i+=86400)
{
    echo $date = date("d-m-Y", $i).' - ';
    echo $dayName = date('l', strtotime($date)).'<br>';
}

My expected results are as under: -

14-12-2018 - Friday 
15-12-2018 - Saturday 
16-12-2018 - Sunday

But what I am getting is: -

14-12-2018 - Thursday 
15-12-2018 - Thursday 
16-12-2018 - Thursday

Upvotes: 0

Views: 616

Answers (2)

John Conde
John Conde

Reputation: 219814

I find using DateTime() and it's related classes makes this much easier. Just create a start and end date with an interval of ne day and use then loop through them to output the days.

$start = new DateTime('2018-12-14');
$end   = (new DateTime('2018-12-16'))->modify('+1 day');
$interval = new DateInterval('P1D');
$period = new DatePeriod($start, $interval, $end);
foreach ($period as $date) {
    echo "{$date->format('d-m-Y - l')}<br>";
}

$start is a DateTime() object and represents the starting day. $end is the last day of the loop. You have to add one day to it as DatePeriod loops are not inclusive of the last day. $interval is a DateInterval() object that represents the interval we want to loop through. In this case a period of one day. $period is a DatePeriod() object and represents all of that information in an iterable object. From there you just loop through it, and with the DateTime() object you are provided with, you simply format as normal.

Result:

14-12-2018 - Friday
15-12-2018 - Saturday
16-12-2018 - Sunday

Demo

Note: this solution rakes daylight savings time and leap year into consideration.

Upvotes: 2

Nigel Ren
Nigel Ren

Reputation: 57121

As you are mixing up the echo and assignments, you are ending up from

echo $date = date("d-m-Y", $i).' - ';

With $date as 14-12-2018- (the extra - on the end). When you try and convert this back to a date in the next line it will fail.

Separate them out and it should work...

for ($i=$date_from; $i<=$date_to; $i+=86400)
{
    $date = date("d-m-Y", $i);
    $dayName = date('l', strtotime($date));
    echo $date .'-'. $dayName.'<br>';
}

Upvotes: 1

Related Questions