In: Computer Science
PHP Question:
Write the PHP code to list out all of the dates of the current month and assign them to their given days. As an example, for the month of October 2020, the output should look something like this:
October 2020
Monday: 5, 12, 19, 26
Tuesday: 6, 13, 20, 27
Wednesday: 7, 14, 21, 28
Thursday: 1, 8, 15, 22, 29
Friday: 2, 9, 16, 23, 30
Saturday: 3, 10, 17, 24, 31
Sunday: 4, 11, 18, 25
IMPORTANT: The code MUST use the current month,
whatever the current month is at the time (so if I used this PHP
code during July of 2020, it would use all of the dates of July
2020 and assign them to the proper days). Do NOT
use tables for this code.
Code
<?php
$now = new \DateTime('now');//get todays data
$month = $now->format('m');//get current month
$year = $now->format('Y');//get current year
$days_in_months=[31,28,31,30,31,30,31,31,30,31,30,31];
//assosiative array that holds the days name and date where this
days comes in this month
$days = [
'Monday' => [],
'Tuesday' => [],
'Wednesday' => [],
'Thursday'=>[],
'Friday'=>[],
'Saturday'=>[],
'Sunday'=>[],
];
for($i=1;$i<$days_in_months[$month-1];$i++)
{
$date = $i.'-'.$month.'-'.$year;
$nameOfDay = date('l', strtotime($date));
if($nameOfDay=="Monday")
array_push($days['Monday'],
$i);
elseif ($nameOfDay=="Tuesday")
array_push($days['Tuesday'],
$i);
elseif ($nameOfDay=="Wednesday")
array_push($days['Wednesday'],
$i);
elseif ($nameOfDay=="Thursday")
array_push($days['Thursday'],
$i);
elseif ($nameOfDay=="Friday")
array_push($days['Friday'],
$i);
elseif ($nameOfDay=="Saturday")
array_push($days['Saturday'],
$i);
else
array_push($days['Sunday'],
$i);
}
echo date('F Y')."</br>";
foreach($days as $x => $x_value)
{
echo "<b>$x:</b>";
$i=0;
for(;$i<count($x_value)-1;$i++)
echo $x_value[$i].", ";
echo $x_value[$i]."</br>";
}
?>
output
If you have any query regarding the code please ask me in the comment i am here for help you. Please do not direct thumbs down just ask if you have any query. And if you like my work then please appreciates with up vote. Thank You.