Need any permutation of capital letters in php

I want to build an array in php containing all possible permutation of a word. so it will be (pseudo code)

function permutate($word){ for ($i=0; $i<count($word); $i++){ ...confused here... array_push($myArray, $newWord) } return $myArray; } 

So let's say that I entered "School", I have to get the array back

{school, school, sChool, SCHool, schOOl, ... SCHOOL}

I know functions that use a string or the first character, but I'm really struggling with how to do this.

+4
source share
1 answer

This should do it for you:

 function permute($word){ if(!$word) return array($word); $permutations = array(); foreach(permute(substr($word, 1)) as $permutation){ $lower = strtolower($word[0]); $permutations[] = $lower . $permutation; $upper = strtoupper($word[0]); if($upper !== $lower) $permutations[] = $upper . $permutation; } return $permutations; } 

Codepad Demo

However, for your specific use case there may be a better solution. Since there are 2^n variables for a string of length n . It is not possible to run this (or even generate all these lines using any method in general) on a much longer line.

In fact, you probably should convert the strings to one specific case before hashing them before storing them in the database if you want to make case insensitive.

+9
source

All Articles