17
$\begingroup$

I have the need to generate a random alphanumeric string of 8 characters. So it should look sort of like b53m1isM for example. Both upper and lower case, letters and numbers.

I already have a loop that runs eight times and what I want it to do is to concatenate a string with a new random character every iteration.

Here's the loop:

$i = 0;
    while($i < 8)
    {
        $randPass = $randPass + //random char
        $i = $i + 1;
    }

Any help?

$\endgroup$
3
  • 1
    $\begingroup$ You use ., not + to concatenate strings in PHP. Also there's $i++; (besides that, you should use a for loop for that) $\endgroup$ Commented Mar 26, 2011 at 19:50
  • $\begingroup$ See stackoverflow.com/questions/5438760/… for answers. $\endgroup$ Commented Mar 26, 2011 at 20:31
  • $\begingroup$ It is wrong to use a while loop for a loop that has to run X times. $\endgroup$ Commented Mar 26, 2011 at 22:05

3 Answers 3

43
$\begingroup$
function getRandomString($length = 8) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $string = '';

    for ($i = 0; $i < $length; $i++) {
        $string .= $characters[mt_rand(0, strlen($characters) - 1)];
    }

    return $string;
}
$\endgroup$
Sign up to request clarification or add additional context in comments.

5 Comments

It would be good to know collision distribution for this scheme. From the limited tests I have run it looks like for N characters, collisions happen after 10^(N-1) tries. Like, if you use 4 chars then collisions will happen after 1000 tries so you should be good for 100 tries at least.
It's random so every character has the same change - i.e. the longer the string the higher the chance of a duplicate character.
I do not think so because here the characters you pick have bias (of mt_rand). Say we were picking two char words. You will hit duplicates much before you expect. you have to consider probability distribution of mt_rand here. it is not a fair draw here.
@ThiefMaster Can you please explain the logic?
What would be a good way to speed this up? I have a use case where this must be used to modify millions of fairly long Unicode strings (~1000 - 2000 chars), but it takes 10 hours to process.
5
$\begingroup$
function randr($j = 8){
    $string = "";
    for($i=0; $i < $j; $i++){
        $x = mt_rand(0, 2);
        switch($x){
            case 0: $string.= chr(mt_rand(97,122));break;
            case 1: $string.= chr(mt_rand(65,90));break;
            case 2: $string.= chr(mt_rand(48,57));break;
        }
    }
    return $string; 
}

echo randr(); // b53m1isM
$\endgroup$

Comments

4
$\begingroup$

Code-golf way:

echo 'm-'.substr(str_shuffle('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'), 0, 16).'.jpg';

// Output: m-swm3AP8X50VG4jCi.jpg

Above method provides pseudo-unique value. Even timestamp more preferable. So the best practice is:

uniqid('prefix_', true);

Or crazy (not KISS) way:

echo 'prefix_'.mb_ereg_replace("[[:punct:]]", '', uniqid(rand(), true)).substr(str_shuffle(implode(array_merge(range('0', '9'), range('a', 'z'), range('A', 'Z')))), 0, 4).'.jpg';
$\endgroup$

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.