Patrick
Patrick

Reputation: 4905

php generate all possible values of characters

I would like a function to generate all possible combination of alphabets. The only parameter the function would need is the number of characters. So for instance if I pass '2', it'll generate:

aa
ab
ac
ad
ae
..
..
zz

If I pass 3, it'll generate:

aaa
aab
...
...
aaz
...
zzz

And so on if I pass 4, etc. Thank you in advance!

Upvotes: 1

Views: 2258

Answers (4)

King Friday
King Friday

Reputation: 26086

See Mark Baker's answer as its the real one. Mine is overly complex not understanding PHP as I don't code in it. Plus, he is just smarter at it seems. :)

<?php 

        function alphabetCombos($length,$prefix = '') {
            for($j = 97; $j < 123; $j++) {
                if ($length > 1) {
                    alphabetCombos($length-1,$prefix . chr($j));
                } else {
                    echo $prefix . chr($j) . '<br />';
                }
            }
        }

        alphabetCombos(2);
?>

Upvotes: 2

Mark Baker
Mark Baker

Reputation: 212422

All these complex nested loops, or use of recursion are totally unnecessary.

Simply use the ++ incrementor with characters.

$string = 'a';
while ($string != 'aaaaa') {
    echo $string++,PHP_EOL;
}

Just watch out for your end loop test... use a != rather than < or > type comparisons

EDIT

So to give you the function you want:

function combinations($size) {
    $string = str_repeat('a',$size);
    $endLoopTest = str_repeat('z',$size);
    $endLoopTest++;
    while ($string != $endLoopTest) {
        echo $string++,PHP_EOL;
    }
}

Upvotes: 12

xkeshav
xkeshav

Reputation: 54032

I can tell u the logic of two words.. you can apply for the rest

foreach ( range('a','z') as $f)
 {
      foreach ( range('a','z') as $s)
      {
          echo "<br/>".$f.$s;
      }
}

reference : range

Upvotes: -1

Grexis
Grexis

Reputation: 1512

Ok, in theory, this works. I couldn't put my computer through the torture of testing it though.

function combinations($pass, $count = null, $l = ''){
    if(is_null($count)) $count = $pass;
    foreach(range('a','z') as $c){
        $k = $l;
        $k .= $c;
        if($count == 1){
            echo $k;
        }else{
            combinations($pass, $count-1, $k);
        }
    }
}

Upvotes: 2

Related Questions