php: How to list from a to z, aa to zz, aA to aZ, and so on

I want to iterate from a to z, A to Z, aa to zz, AA to ZZ, aA to zZ, Aa to Zz, and so on. And of course with any length.

for example:

$length = 2;
$limit = str_repeat('z', $length);
for($i='a';$i<=$limit;$i++) {
    if($i==str_repeat('a', $length+1)) break; // stop on 'aaa';
    myCallback($i);
}

the result will be:

a
b
c
...
z
aa
ab
ac
...
zz

So, I want to create something exactly like this, but with upper, small, and both.

Answer

function generate($length = 1) {
    $small = range('a', 'z');
    $capital = range('A', 'Z');
    if ($length <= 0) {
        return [];
    } elseif ($length == 1) {
        return array_merge($small, $capital);
    } else {
        $result = [];
        foreach (array_merge($small, $capital) as $letter) {
            foreach (generate($length - 1) as $subLetter) {
                $result[] = $letter . $subLetter;
            }
        }
        return $result;
    }
}

// Sample output
echo '<pre>' . print_r(generate(2), true) . '</pre>';

Try it online

Leave a Reply

Your email address will not be published. Required fields are marked *