Learn how to generate a structure of directories from the A to the Z automatically with a short script in PHP.

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:


// 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 !

Senior Software Engineer at Software Medico. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.