Generate random number in PHP

When you need to save multiple files in same directory, then you need to generate random number everytime. Generating random numbers in PHP can be done by many ways.

In this article, we will discuss built-in functions which can be used to generate random numbers in PHP.

rand() function

The rand() function generates a random integer value.

Syntax

rand($min, $max)

Parameters

$min optional, default 0
$max optional default getrandmax()(2147483647)
<?php

echo(rand()); // 14870

If you want to get values between two digits, include these parameters. Suppose you want random number between 100 and 1000, pass them in function arguments.

<?php

echo(rand(100, 1000)); // 458

mt_rand() function

Generate random number using the Mersenne Twister Random number generator. This is four times faster and more secure than rand() function.

Syntax

mt_rand($min, $max)

Parameters

$min optional, default 0
$max optional default mt_getrandmax()
<?php

echo mt_rand(); // 14314917

mt_rand() function also accepts two arguments, minimum and maximum integer value. It will return integer number between minimum and miximum number.

<?php

echo mt_rand(100, 1000); // 752

random_int() function

random_int() function generates cryptographically secured pseudo-random integer number.

Syntax

random_int($min, $max)

Parameters

$min the minimum number to be returned, should be PHP_INT_MIN or higher
$max The highest number to be returned, should be less than or equal to PHP_INT_MAX.
<?php

echo(random_int(100, 1000)); // 459
echo(random_int(-1000, -100)); // -121

 

Tags:

Was this article helpful?

0 out of 0 person found this article helpful.

Leave a comment

Or

No Comment