user1032531
user1032531

Reputation: 26281

Warning: mt_rand(): max(-1) is smaller than min(1)

The following script provides the following output. I am running PHP Version 5.5.12 with Apache/2.2.15 (CentOS) on i386 server. Note I run the same script on my almost identical server which is x86_64, and I don't experience the error.

<?php
$id=mt_rand ( 1 , 4294967295);
?>

Warning: mt_rand(): max(-1) is smaller than min(1) in /var/www/html/testing/mt_rand.php on line 2

What causes this error, and how do I fix it?

Upvotes: 1

Views: 4987

Answers (2)

user1032531
user1032531

Reputation: 26281

If you want a value between 1 and 4294967295 which is platform independent, use the following:

$id=2147483648+mt_rand(-2147483647,2147483647);

This answers part of the question, but fedorqui answered the real question that an integer on some platforms is limited to +/-2,147,483,647.

Upvotes: 3

fedorqui
fedorqui

Reputation: 289915

You happen to use a value that is bigger than the integer maximum. As read in What is the maximum value for a int32?, this value is 2,147,483,647.

From PHP.net in mt_rand():

Description

int mt_rand ( void )

int mt_rand ( int $min , int $max )

Return Values

A random integer value between min (or 0) and max (or mt_getrandmax(), inclusive), or FALSE if max is less than min.

From the PHP manual:

The size of an integer is platform-dependent, although a maximum value of about two billion is the usual value (that's 32 bits signed). PHP does not support unsigned integers. Integer size can be determined using the constant PHP_INT_SIZE, and maximum value using the constant PHP_INT_MAX since PHP 4.4.0 and PHP 5.0.5.

Your script fails on 32 bits systems because you are providing a value which is ~4 billion, while the maximum is ~2 billion. A workaround can be to change PHP_INT_MAX.

Upvotes: 2

Related Questions