How to generate automatically an alphabetic structure of directories wih PHP (A to Z)

Recently while working on a project that required alphabetic indexation, a very trivial problem showed up asking to myself how to automatize the creation of a structure of directory that contains a folder named as every character of the alphabet. Obviously, i was not going to create manually the dictionary from A to Z knowing that PHP offers a method, namely range, that allows me to create an array containing a range of elements providing the start and the end of the sequence.

The creation of the directories can be easily done with the mkdir method, so creating a variable that contains the created range, you can iterate over it with a foreach statement, creating every directory in the specified directory:

<?php

// generate array with the characters from the alphabet 
// A to Z
$alphabet = range("a", "z");
        
// Iterate over every character and create a directory with the name of the current character
foreach($alphabet as $character){
    mkdir("./" . $character);
}

We created them in the current directory, where the script runs. So after its execution, you will find a structure of directories named just like the alphabet:

./
├── 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/

Happy coding !

This could interest you

Become a more social person