Random number in range [min - max] using PHP

Here, we are going to learn how to generate random integers between the given ranges (start value and end value) in PHP?
Submitted by IncludeHelp, on April 06, 2019 [Last updated : March 12, 2023]

Random integer number generation

To generate a random integer, we can use random_int() function, which is a library function in PHP, it accepts two arguments start_value and end_value and returns a random integer between start_value and end_value.

PHP program to generate a random integer between the ranges

<?php
    $start = 10;
    $end = 20;
    
    //generating 10 number
    print("random integers between $start and $end...\n");
    for($i=1; $i<=10; $i++)
    {
        print(random_int($start, $end)." ");
    }
    print("\n");
    
    $start = -100;
    $end = 0;    

    //generating 10 number
    print("random integers between $start and $end...\n");
    for($i=1; $i<=10; $i++)
    {
        print(random_int($start, $end)." ");
    }    
?>

Output

random integers between 10 and 20...
15 15 16 17 10 15 15 13 14 13
random integers between -100 and 0...
-84 -4 -68 -36 -18 -56 -53 -31 -98 -94

PHP Basic Programs »





All PHP Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.