Code Snippet, Every Character Case Combination

Coding Critique is the place to post source code for peer review by other members of DevNetwork. Any kind of code can be posted. Code posted does not have to be limited to PHP. All members are invited to contribute constructive criticism with the goal of improving the code. Posted code should include some background information about it and what areas you specifically would like help with.

Popular code excerpts may be moved to "Code Snippets" by the moderators.

Moderator: General Moderators

Post Reply
User avatar
Jonah Bron
DevNet Master
Posts: 2764
Joined: Thu Mar 15, 2007 6:28 pm
Location: Redding, California

Code Snippet, Every Character Case Combination

Post by Jonah Bron »

This script gives every possible uppercase/lowercase combination. I wrote it in response to a question (viewtopic.php?t=116886). Apollo also answered; his is slightly faster, but also slightly longer (thanks to him for one optimization).

Mine uses an incrementing binary number with the same number of digits as characters in the string. The 1s and 0s dictate the uppercase/lowercase combination. So without further adieu, here's the code...

Code: Select all

function AllCases($s)  {
    $s = strtolower($s);
    $s2 = strtoupper($s);
    $c = array();
    $l = strlen($s);
    for ($i = 0, $t = bindec(str_pad('', $l, '1')); $i <= $t; $i++){
        $c[] = $s;
        $x = str_pad(decbin($i), $l, '0', STR_PAD_LEFT);
        for ($w = 0; $w < $l; $w++){
            $c[$i][$w] = ($x[$w] === '1') ? $s2[$w] : $s[$w];
        }
    }
    return $c;
}
If the string you give it has non-alphanumeric chars, you might want to run array_unique on the result.

It would be faster if I could increment the binary number directly instead of converting it every time. Does anyone know if PHP can do that?
Post Reply