DEV Community

Aaron Junker
Aaron Junker

Posted on • Originally published at blog.aaron-junker.ch

3 2

Looping through letters and dates in PHP with the for loop

Inspired by: https://bit.ly/2ZmgKGT and https://bit.ly/3u7oSZO

Did you know that you can loop through letters in a for loop? It’s simple as the example below shows:

<?php
    for($char = 'A'; $char != 'AA'; $char++){
        echo $char.' ';
    }
?>
Enter fullscreen mode Exit fullscreen mode

The result:

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
Enter fullscreen mode Exit fullscreen mode

After Z it’s starting from AA to AZ to ZZ and then from AAA to AAZ to AZZ to BAA and so on.
It can’t go before A. That means the following code just prints out a bunch of A's:

<?php
    for($char = 'A'; $char != 'AA'; $char--){
        echo $char.' ';
    }
?>
Enter fullscreen mode Exit fullscreen mode

You can also loop through dates:

<?php
    $start = strtotime("2021-01-01");
    $end = strtotime("2021-02-01");
    $count = strtotime("+2 day", $date);
    for($date = $satrt; $date < $end; $date = $count) {
        echo date("Y-m-d", $date)."<br />";
    }
?>
Enter fullscreen mode Exit fullscreen mode

This example prints out every second date between the January 1st and February 1st.

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay