How to find all the sundays of a year in PHP

In this article, we will discuss how to find all the Sundays of a year in PHP. PHP provides various methods to handle the date data in an efficient manner.

How to find all the Sundays in PHP

PHP feature strtotime() and date() methods to retrieve the date and time data from the methods.

The below example illustrates script to find all Sundays in a year,

<?php

function getSunday($startDt, $endDt, $weekNum)
{
    $startDt = strtotime($startDt);
    $endDt = strtotime($endDt);

    $dateSun = array();

    do
    {
        if(date("w", $startDt) != $weekNum)
        {
            $startDt += (24 * 3600); // add 1 day
        }
    } while(date("w", $startDt) != $weekNum);


    while($startDt <= $endDt)
    {
        $dateSun[] = date('d-m-Y', $startDt);
        $startDt += (7 * 24 * 3600); // add 7 days
    }

    return($dateSun);
}

$year   = date("Y");//You can add custom year also like $year=1997 etc.

$dateSun = getSunday($year.'-01-01', $year.'-12-31', 0);
echo"<pre>slno.     Date<br>";
foreach($dateSun as $index => $date)
{
  echo ($index+1).'       '.$date.'<br>';
} 
?>

 

Output:-

slno.     Date
1       06-01-2019
2       13-01-2019
3       20-01-2019
4       27-01-2019
5       03-02-2019
6       10-02-2019
7       17-02-2019
8       24-02-2019
9       03-03-2019
10       10-03-2019
11       17-03-2019
12       24-03-2019
13       31-03-2019
14       07-04-2019
15       14-04-2019
16       21-04-2019
17       28-04-2019
18       05-05-2019
19       12-05-2019
20       19-05-2019
21       26-05-2019
22       02-06-2019
23       09-06-2019
24       16-06-2019
25       23-06-2019
26       30-06-2019
27       07-07-2019
28       14-07-2019
29       21-07-2019
30       28-07-2019
31       04-08-2019
32       11-08-2019
33       18-08-2019
34       25-08-2019
35       01-09-2019
36       08-09-2019
37       15-09-2019
38       22-09-2019
39       29-09-2019
40       06-10-2019
41       13-10-2019
42       20-10-2019
43       27-10-2019
44       03-11-2019
45       10-11-2019
46       17-11-2019
47       24-11-2019
48       01-12-2019
49       08-12-2019
50       15-12-2019
51       22-12-2019
52       29-12-2019

Note:-

  • In the above script, “w” displays the week number from the date().
  • In the above script, the method date(“Y”) returns the current year. You can also manually assign it. For example:-$date=2014;

If you have any doubts about this article, leave a comment below.




See also,


Leave a Reply

Your email address will not be published. Required fields are marked *