all string combinations in a fixed length, based on a charset

I’m looking to create a function that will return every possible string within a given string length, using a charset.

As an example, a charset of “abc”, and a length of 2 should allow for 9 (3 ^ 2) unique combinations:


(List constructed manually)

What method could be used to create such a function?

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

As always, there are multiple ways to solve what you ask for, this is only one way, using one counter per character in the output string:

$c = "abc"; // charset
$l = 2; // string length

for($t='',$cl=strlen($c),$s=array_fill(0,$l,0),$i=pow($cl,$l);$a=0,$i--;) {
    for($t&&$t.=', ';$a<$l;$t.=$c[$s[$a++]]);

echo $t; // the string you asked for.

aa, ab, ac, ba, bb, bc, ca, cb, cc

One main loop, one loop to build the string and one loop for counting up.

I can imagine this should work with getting modulos per each position of the output string as well.

Solution 2

You already did go about this, as we can plainly see from your example solution:

aa, ab, ac, ba, bb, bc, ca, cb, cc

What did you do in your head to come up with this solution? You had to keep a few things in mind:

  1. what’s the char I should start with from charset?

  2. as I am constructing the output string, what’s the next char from charset?

  3. how many chars am I allowed to pick from charset?

  4. what must I do when I’ve picked from charset all the chars that I’m allowed to?

  5. have I exhausted charset with respect to chars I can start with? if yes, I’m finished.

Can you translate this into code? Or is this answer just too cutesy?

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply