Generating random PHP string
There is an easy way for doing this, by using just a few lines of code.
The first thing we need to consider is what kind of string we want to create.
You have to ask yourself do I want to use 0-9 or a-z or both. We will define these characters in PHP first
In case of both a-z (lowcase) and 0-9 we will create the following PHP string of available characters :
$availableCharacters = "0123456789bcdfghjkmnpqrstvwxyz";
After this we create our empty string in which the random string will be placed.
It's always good to do this first because we want to make sure we start with an empty string.
In the second line we reset our counter to zero for later.
$randomString = ""; $counter = 0;
Now the most essential part that we will use to randomly create our now string.
Sidenote : 120 represents the length of the new random string.
do{$randomString.=substr($availableCharacters, mt_rand(0, strlen($availableCharacters)-1), 1);++$counter;}while($counter<120);
After this line we completed the proces of generating a random PHP string.Performance : Using do -> while is pretty much the fastest way to perform a while loop.
The complete code:
$availableCharacters = "0123456789bcdfghjkmnpqrstvwxyz";
$randomString = "";
$counter = 0;
do{$randomString.=substr($availableCharacters, mt_rand(0, strlen($availableCharacters)-1), 1);++$counter;}while($counter<120);
Posted by James on 2009-05-02 in the category " php "
