Search code examples
phpdatestrtotime

PHP - Get dates of next 5 weekdays?


I'm trying to create an array of the next 5 working week days (Monday - Friday, excluding today). I know the working week varies around the world but this is not important for what I am trying to do.

So, for example, if today is a Wednesday, I want the dates for Thursday and Friday of the current week and Monday, Tuesday and Wednesday of the following week.

I thought this would work:

$dates = array();

for ($i = 1; $ < 6; $i ++)
{
    $dates[] = date('Y-m-d', strtotime('+ '.$i.' weekday'));
}

But for today, it is giving me:

  • Monday 1st
  • Tuesday 2nd
  • Wednesday 3rd
  • Thursday 4th
  • Sunday 7th!

Any advice appreciated.

Thanks


Solution

  • Try this

    $dates = array();
    $date = new DateTime();
    
    while (count($dates)<5)
    {
        $date->add(new DateInterval('P1D'));
        if ($date->format('N')<6)
            $dates[]=$date->format('Y-m-d');
    }