Write a program to find the 1st of January will be a Sunday between 2014 and 2050 in php

By toswebdev, 19 January, 2023
Write a program to find the 1st of January will be a Sunday between 2014 and 2050 in php

Here is an example of a PHP program that will find all the years between 2014 and 2050 in which January 1st is a Sunday:

<?php
for ($year = 2014; $year <= 2050; $year++) {
   $date = strtotime("1 January $year");
   if (date("l", $date) == "Sunday") {
       echo "1st January is being a Sunday ".  $year . " </br>";
   }
}
?>

The program uses a for loop to iterate through the years between 2014 and 2050, and for each year, it creates a timestamp for January 1st using the strtotime() function. Then it uses the date() function with the "l" format option to get the day of the week for that date. If the day of the week is "Sunday", the year is printed on the screen using the echo statement.

Please note that this code is for demonstration purposes only and it is not optimized for performance.
Sure, here is an explanation of each line of the code:

  1. for ($year = 2014; $year <= 2050; $year++) {: This line starts a for loop that will iterate through the years between 2014 and 2050. The variable $year is initialized to 2014, and the loop will continue running until $year is greater than 2050.
  2. $date = strtotime("1 January $year");: This line creates a timestamp for January 1st of the current year in the loop using the strtotime() function. The string "1 January $year" is passed as an argument to the function, with the current value of $year being used to specify the year. The resulting timestamp is stored in the variable $date.
  3. if (date("l", $date) == "Sunday") {: This line uses the date() function to get the day of the week for the timestamp stored in $date. The "l" format option is used to get the full name of the day of the week. The result is then compared to the string "Sunday" using the comparison operator (==). If the day of the week is Sunday, the code inside the curly braces will be executed.
  4. echo "1st January is being a Sunday ".  $year . " </br>";: This line is inside the if statement, so it will only be executed if the day of the week is Sunday. It uses the echo statement to print the current year to the screen, followed by a new line character (<br>) to start a new line for the next year.
  5. } : This line closes the if statement.
  6. } : This line closes the for a loop.
  7. ?> : This line is the end of the PHP script.

The code will find all the years between 2014 and 2050 in which January 1st is a Sunday and print them out with a new lines.
 

Comments

All comments go through moderation, so your comment won't display immediately.