Categories: Development

Loop through all days in month with PHP

Looping through all the days in the current month with PHP.

This loop will start at the first day of the current month with each loop adding 1 day, the loop will continue until the current month is no longer less than or equal to the last looped day/date.

<?php
$date = date('F Y');//Current Month Year
while (strtotime($date) <= strtotime(date('Y-m') . '-' . date('t', strtotime($date)))) {
    $date = date("Y-m-d", strtotime("+1 day", strtotime($date)));//Adds 1 day onto current date
}

Now to add in some formatted DateTime values:

$day_num = date('j', strtotime($date));//Day number
$day_name = date('l', strtotime($date));//Day name
$day_abrev = date('S', strtotime($date));//th, nd, st and rd
$day = "$day_name $day_num$day_abrev";

The full script:

<?php
$date = date('F Y');//Current Month Year
while (strtotime($date) <= strtotime(date('Y-m') . '-' . date('t', strtotime($date)))) {
    $day_num = date('j', strtotime($date));//Day number
    $day_name = date('l', strtotime($date));//Day name
    $day_abrev = date('S', strtotime($date));//th, nd, st and rd
    $day = "$day_name $day_num $day_abrev";
    $date = date("Y-m-d", strtotime("+1 day", strtotime($date)));//Adds 1 day onto current date
    echo $day . '<br>';
}

This will output (As for October 2020):

Thursday 1st
Friday 2nd
Saturday 3rd
Sunday 4th
Monday 5th
Tuesday 6th
Wednesday 7th
Thursday 8th
...

You can change the date formating with values from here.

Share

Recent Posts

Kennington reservoir drained drone images

A drained and empty Kennington reservoir images from a drone in early July 2024. The…

1 year ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

1 year ago

FTP getting array of file details such as size using PHP

Using FTP and PHP to get an array of file details such as size and…

2 years ago

Creating Laravel form requests

Creating and using Laravel form requests to create cleaner code, separation and reusability for your…

2 years ago

Improving the default Laravel login and register views

Improving the default Laravel login and register views in such a simple manner but making…

2 years ago

Laravel validation for checking if value exists in the database

Laravel validation for checking if a field value exists in the database. The validation rule…

2 years ago