Here is my code
<?php
function random_id() {
$chars = 'abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ';
$id = '';
for ($i = 0; $i < 5; ++$i)
{
$id .= $chars[rand(1, 26)];
}
echo $id;
}
random_id();
?>
It keeps generating IDs with 5 lowercase digits, and VERY occasionally it will have a number in it. I tried with mt_rand() as well, and also using srand(time()) and srand(microtime()) at the beginning of the script before the loop.
Also, should it be rand(1, 26) or rand(0, 25)?
Your string is longer than 26 characters. Use this rand function instead:
So that you’re not calculating string length on every iteration, but still keeping it dynamic, it is worth considering moving the calculation outside of the loop like so: