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…

2 years ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

2 years ago

Early September spring shots

Some early September spring shots from a bushwalk, It is still too early for wildflowers.

3 years ago

Cloning an NVMe to SK Hynix Platinum P41 NVMe

I recently needed to clone over a smaller NVMe to a 2TB SK Hynix Platinum…

3 years ago

Using Laravel’s deleteDirectory to delete folders and their contents

If you ever needed a simple solution in Laravel to delete an entire directory and…

3 years ago

How to allow only 1 user to register in a Laravel application

How to enforce only one user to register or be registered in a Laravel web…

3 years ago