Danny Franklin
Danny Franklin

Reputation: 45

mt_rand and rand not working (PHP)

I am having a problem where by when I try and generate numbers randomly with either mt_rand or rand (on a larger scale) I get no result at all. This used to work fine on my server but there seems to be issues now and I am unsure why.

<?php
echo 'Your number is: '.rand(0, 99999999999999999999);
?>

Where as it I update it to something like (using a 9 digit number):

<?php
echo 'Your number is: '.rand(0, 999999999);
?>

the lower example will work fine. I have recently changed my server version PHP 7.0. Is there a way to increase the maximum number or a better way to be doing this? Thanks.

Upvotes: 1

Views: 4448

Answers (3)

kodmanyagha
kodmanyagha

Reputation: 1005

Microtime generated random everytime.

function microtimeRand( $min, $max ) {
    $microtimeInt = intval( microtime( true ) * 100 );
    $microtimeInt = $microtimeInt % ($max - $min);
    $microtimeInt += $min;

    return $microtimeInt;
}

Upvotes: 0

mystery
mystery

Reputation: 19533

On both 32-bit and 64-bit systems, the number 99999999999999999999 is too large to be represented as an integer in PHP 7, so it becomes a float.

However, mt_rand() takes two integers. Because 99999999999999999999 is too large to be an integer, when you pass it to the function, PHP 7 throws an error, because it cannot be safely converted. You didn't get this error for 999999999, because it's small enough to be an integer.

Anyway, your current code probably isn't doing that you want under PHP 5: 99999999999999999999 is being silently converted to 7766279631452241920 on 64-bit systems, and something else on 32-bit systems. So you're not getting the full range of random numbers. You wrote rand(0, 99999999999999999999), but you're actually getting rand(0, 7766279631452241920).

If you just want a random number from the widest possible range, try this:

<?php
echo 'Your number is: '.rand(0, PHP_INT_MAX);
?>

PHP_INT_MAX is a constant containing the largest possible integer (which will be different depending on whether you're on 32-bit or 64-bit). So, doing this will always give you the widest possible range of random positive numbers from that function.

Upvotes: 2

Sumit Kumar
Sumit Kumar

Reputation: 580

To run the code in php 7 you have to typecast

<?php
echo 'Your number is: '.rand(0,(int) 99999999999999999999);
?>

Upvotes: 1

Related Questions