The rand(), mt_rand(), and lcg_value() functions are used to generate random numbers in PHP. These functions have different performance characteristics and are used depending on whether you need integers or floating-point random values.
rand().rand(min, max) → Integer between min and maxmt_rand(min, max) → Faster integer generator using Mersenne Twisterlcg_value() → Float between 0 and 1 using linear congruential generator
// Generate a random integer between 1 and 100 using rand()
<?php
$random_number = rand(1, 100);
echo $random_number;
?>
Each execution generates a different integer between 1 and 100. The values are pseudo-random and suitable for basic use cases.
// Generate a faster and more reliable random number using mt_rand()
<?php
$random_number = mt_rand(1, 100);
echo $random_number;
?>
mt_rand() behaves like rand() but uses a more efficient algorithm (Mersenne Twister), making it ideal for performance-critical applications.
// Generate a random floating-point number between 0 and 1
<?php
$random_float = lcg_value();
echo $random_float;
?>
This function is commonly used in simulations and scenarios where fractional random values are required.
You can combine lcg_value() with math operations to simulate percentages or probabilities, such as random discounts or probability-based decisions.
mt_rand() over rand() for better performance.lcg_value() when you need floating-point randomness.random_int() or random_bytes().mt_rand(1, 6).lcg_value().