Printing numbers within a range in PHP

random numbers

random numbers

The following PHP source code shows that how to print random numbers within a range using a seed. It uses rand() function to return the random numbers within a predefined range. The srand() function is used to provide the seed or arbitrary int number.

The rand() is built in PHP function which is generally used to generate a random integer number with in a range of values i.e., it can generate a random integer value in the range [min, max].

This function is not very secure so it should not be used for cryptographic purposes. Your can consider using any of these functions if you need a cryptographically secure value random_int()random_bytes(), or openssl_random_pseudo_bytes() instead.

<?php
 srand(time());

 //get ten random numbers from -100 to 100
 for($index = 0; $index < 10; $index++)
 {
  print(rand(-100, 100) . "<br>\n");
 }
?>

Note: The output of the code changes every time it is run because we provide a different seed every time by using srand(time()) function.

Output:

-49
50
60
32
59
-7
-94
-31
97
-41
Categories: PHP Source Code
M. Saqib: Saqib is Master-level Senior Software Engineer with over 14 years of experience in designing and developing large-scale software and web applications. He has more than eight years experience of leading software development teams. Saqib provides consultancy to develop software systems and web services for Fortune 500 companies. He has hands-on experience in C/C++ Java, JavaScript, PHP and .NET Technologies. Saqib owns and write contents on mycplus.com since 2004.
Related Post