I know that the rand function in PHP generates random integers, but what is the best way to generate a random string such as:
Original string, 9 chars
$string = 'abcdefghi';
Example random string limiting to 6 chars
$string = 'ibfeca';
UPDATE: I have found tons of these types of functions, basically I'm trying to understand the logic behind each step.
UPDATE: The function should generate any amount of chars as required.
Please comment the parts if you reply.
If you want to allow repetitive occurences of characters, you can use this function:
The basic algorithm is to generate <length> times a random number between 0 and <number of characters> − 1 we use as index to pick a character from our set and concatenate those characters. The 0 and <number of characters> − 1 bounds represent the bounds of the
$charset
string as the first character is addressed with$charset[0]
and the last with$charset[count($charset) - 1]
.My favorite:
Do you want to create your password by a random permutation of the original letters? Should it just contain unique characters?
Use
rand
to choose random letters by index.Well, you didn't clarify all the questions I asked in my comment, but I'll assume that you want a function that can take a string of "possible" characters and a length of string to return. Commented thoroughly as requested, using more variables than I would normally, for clarity:
To call this function with your example data, you'd call it something like:
Note that this function doesn't check for uniqueness in the valid chars passed to it. For example, if you called it with a valid chars string of
'AAAB'
, it would be three times more likely to choose an A for each letter as a B. That could be considered a bug or a feature, depending on your needs.If you're not concerned about time, memory, or cpu efficiency, and if your system can handle it, why not give this algorithm a try?!
Maybe this will read better if it uses recursion, but I'm not sure if PHP uses tail recursion or not...
Updated the code as per mzhang's great suggestion in the comments below.