Generate Random Numbers in PHP
Complete code tutorial with examples and best practices
[ Code Example - Quick Summary ]
Language: PHP
What: Generate cryptographically secure random numbers in PHP using the <code>random_int()</code> function. This modern approach provides better security than older methods like <code>rand()</code> or <code>mt_rand()</code>.
Try it: Use our interactive Numbers generator or integrate this code into your PHP application.
Generate cryptographically secure random numbers in PHP using the random_int() function. This modern approach provides better security than older methods like rand() or mt_rand().
Looking for other languages? Check our code examples in
JavaScript
,
Python
,
Java
,
C#
,
C++
,
Ruby
and
Go
or use our interactive web generator.
PHP Code Example
<?php
// Generate a single random number between 1 and 100
$randomNumber = random_int(1, 100);
echo $randomNumber; // Example output: 42
// Generate multiple random numbers
$numbers = [];
for ($i = 0; $i < 10; $i++) {
$numbers[] = random_int(1, 100);
}
print_r($numbers);
// Example output: [23, 7, 91, 45, 12, 68, 3, 89, 54, 31]
// Generate random float/decimal
$randomFloat = random_int(0, 10000) / 100; // 0.00 to 100.00
echo number_format($randomFloat, 2); // Example: 42.17
[EXPLANATION]
The random_int() function generates cryptographically secure random integers. It takes two parameters: the minimum and maximum values (inclusive). For random floats, divide a large random integer by a power of 10 to get the desired precision.
Expected Output
42
Array
(
[0] => 23
[1] => 7
[2] => 91
[3] => 45
[4] => 12
[5] => 68
[6] => 3
[7] => 89
[8] => 54
[9] => 31
)
42.17
Common Use Cases
- Generating unique session IDs or tokens
- Creating lottery or raffle number combinations
- Random sampling for A/B testing
- Game mechanics (dice rolls, card shuffling)
- Statistical simulations and Monte Carlo methods
- Test data generation for QA environments
Important Notes
-
random_int()is available in PHP 7.0+ -
Use
random_bytes()for raw random bytes -
Avoid using
rand()ormt_rand()for security-critical applications - For backwards compatibility with PHP 5.x, use a polyfill library
Try Our Interactive Generator
Don't want to write code? Use our free web-based Numbers generator with instant results.
TRY NUMBERS GENERATOR →Other Programming Languages
View Numbers generation code examples in JavaScript
View Numbers generation code examples in Python
View Numbers generation code examples in Java
View Numbers generation code examples in C#
View Numbers generation code examples in C++
View Numbers generation code examples in Ruby
View Numbers generation code examples in Go