Posts

Finding all the Weekdays in the month with Php

Hello friends. Today, I had to find every weekdays in the month, including the week we were there. Using the codes you write as you wish, you can get the days you want. It’s simple. You can only know the DateTime class.

I only collect weekdays on a array. I do not include weekends. After I set this $lastDay variable to Friday, I update the $lastDay variable to be 3 days later at the beginning of each loop. So I find the monday and push each day into the array separately.

<?php

// Set Today
$today = new DateTime();
// Find beginning of the week
$monday = clone $today;
$monday = $monday->modify(('Sunday' == $monday->format('l')) ? 'Monday last week' : 'Monday this week');
// I will set the variable $lastDay in the loop to the previous week's date. So I can update it on a Monday.
$lastDay = clone $monday;
$lastDay = $lastDay ->modify('-3 day');
// We create an array that specifies 5 weeks.
$dates = array(
    "week1" => array(),
    "week2" => array(),
    "week3" => array(),
    "week4" => array(),
    "week5" => array()
);
// We are starting loop. Here we put our $dates array into foreach.
foreach ($dates as $key => $date) {
    // We use the $lastDay variable to find the first day of the week.
    $firstDay = clone $lastDay;
    $firstDay = $firstDay->modify('+3 day');
    // After that, we increase the days to finding the remaining 4 days.
    $secondDay = clone $firstDay;
    $secondDay = $secondDay->modify('+1 day');
    $thirdDay = clone $secondDay;
    $thirdDay = $thirdDay->modify('+1 day');
    $forthDay = clone $thirdDay;
    $forthDay = $forthDay->modify('+1 day');
    $fifthDay = clone $forthDay;
    $fifthDay = $fifthDay->modify('+1 day');
    // We set the $lastDay variable to the 5th day, ie Friday. In this way, we will be able to find Monday at beginning of the loop.
    $lastDay = clone $fifthDay;
    // I am adding dates to the corresponding week in the $date array. I used different indexes here. You can edit it as you like.
    $dates[$key] = array(
        $firstDay->format('M d D') => $firstDay->format('Y-m-d'),
        $secondDay->format('M d D') => $secondDay->format('Y-m-d'),
        $thirdDay->format('M d D') => $thirdDay->format('Y-m-d'),
        $forthDay->format('M d D') => $forthDay->format('Y-m-d'),
        $fifthDay->format('M d D') => $fifthDay->format('Y-m-d'),
    );
}