View Full Version : Random Number Gen Length Problem

12-12-2008, 10:18 AM

I'm using the following code to generate a random 12 digit string. However, for some reason its intermittently creating 11 digit strings.

function genRandomString() {
$length = 12;
$characters = '0123456789ABCDEFGHJKMNPQRSTUVWXYZ';
$string = '';

for ($p = 0; $p < $length; $p++) {
$string .= $characters[mt_rand(0, strlen($characters))];

return $string;

The last string returned was 3E4P5BFSERB - 11 digits and the time prior to that was VGM5V4GJGGH3 - 12 digits. Is there any reason why its sometimes only returning an 11 digit string?



P.S. I know some letters are missing from the available characters, I removed letters that could be mistaken for numbers, i.e. o = 0, i & l = 1 etc, this way if you hand write the string you can't get it wrong.

12-12-2008, 10:29 AM
$characters[mt_rand(0, strlen($characters))];
Array out of bound issue. It should be

$characters[mt_rand(0, strlen($characters)-1)];

12-12-2008, 10:55 AM
Ah I see!

That seems to have fixed the problem, just test generated 3 more strings, and each was 12 digits.

Thanks for your help