DEV Community

Aaron Junker
Aaron Junker

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

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.

Top comments (0)