Random Number Generator in PHP 8.4

Hello Friends Today, through this tutorial, I will tell you how to random number generator that works in PHP 8.4 Language Program.This solution generates numbers with 4, 6, 8, and 10 digits.

<?php
function generateRandomNumber(int $digits): string {
if ($digits < 1) {
throw new InvalidArgumentException("Number of digits must be at least 1");
}
$min = 10 ** ($digits - 1);
$max = (10 ** $digits) - 1; 
return (string) random_int($min, $max);
}
// Generate and display random numbers
echo "4-digit random number: " . generateRandomNumber(4) . "\n";
echo "6-digit random number: " . generateRandomNumber(6) . "\n";
echo "8-digit random number: " . generateRandomNumber(8) . "\n";
echo "10-digit random number: " . generateRandomNumber(10) . "\n";
?>

How It Works?

1. The generateRandomNumber function takes the number of digits as input.
2. It calculates the minimum possible number for that digit count (e.g., 1000 for 4 digits).
3. It calculates the maximum possible number for that digit count (e.g., 9999 for 4 digits).
4. It uses PHP’s random_int() which is cryptographically secure.
5. The result is returned as a string to preserve leading zeros (though with this range there won’t be any).