Finding the Days of the Week with PHP
Hello friends. Today, I had to find the days of each of the five weeks, including the current week. You can use the codes I wrote however you like to get the days you want. The logic is simple. DateTime You just need to know the class.
I'm simply collecting the weekdays in an array. I set the $lastDay variable to Friday, then update it three days in the future at the beginning of the loop. This way, I find Monday and enter each day individually into the array.
// We create today $today = new DateTime(); // We find the beginning of the current week. $monday = clone $today; $monday = $monday->modify(('Sunday' == $monday->format('l')) ? 'Monday last week' : 'Monday this week'); // I set the $lastDay variable in the loop I will create to Friday of the previous week. This way, I will be able to update it to Monday. $lastDay = clone $monday; $lastDay = $lastDay ->modify('-3 day'); // We create our array that specifies 5 weeks. $dates = array( "week1" => array(), "week2" => array(), "week3" => array(), "week4" => array(), "week5" => array() ); // Let's start our loop. Here we put our $dates array in foreach. foreach ($dates as $key => $date) { // We find the first day of the week using the $lastDay variable. $firstDay = clone $lastDay; $firstDay = $firstDay->modify('+3 day'); // After that, we find the remaining 4 days by incrementing each day by one. $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, which is Friday. This way, we will be able to find Monday at the beginning of the loop. $lastDay = clone $fifthDay; // I add the days to the relevant week in the $date array. I used different indexes here. You can arrange them however you want. $dates[$key] = array( $firstDay->format('M d D') => $firstDay->format('Ym-d'), $secondDay->format('M d D') => $secondDay->format('Ym-d'), $thirdDay->format('M d D') => $thirdDay->format('Ym-d'), $forthDay->format('M d D') => $forthDay->format('Ym-d'), $fifthDay->format('M d D') => $fifthDay->format('Ym-d'), ); }