Page 1 of 1

Code Snippet, Every Character Case Combination

Posted: Thu May 27, 2010 5:09 pm
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?