How to Generate Random Number in PHP
Hello developers, in this short tutorial, we will learn how to generate random number in PHP.
In many case, we may require to generate random number in PHP. It may be testing purpose, or may be id or number generation, or may be simply load testing. In PHP we can easily generate random number easily by using function.
The basic structure of the function to generate random number is:
rand() or rand(min, max)
So lets check these out with example:
<?php echo(rand() . "<br>"); // This will print a random number echo(rand(1,50). "<br>"); // This will print a random number between 1 and 50 echo(rand(1000,9999). "<br>"); // This will print a random number between 1000 and 9999 ?>
Output:
1801702658 48 6028
Parameters:
Parameter | Description | Required/Optional |
---|---|---|
min | Specifies the lowest number to be returned. | Optional |
max | Specifies the highest number to be returned. | Optional |
Let’s say, for a lottery you have to randomly pick 100 winners. Than you have to define users range and run below programs to randomly select 100 winners.
<?php $no_of_digits = 100; $var=''; for($i=1; $i <= $no_of_digits; $i++){ $var .=rand(0,99).'<br>'; } echo "<br>Random Value = <br> $var"; ?>
That’s all for today. If you have any questions, you can comment below. If you loved this article, show love by sharing the article who might need it.
Have a nice day. Keep learning! See you in the next one.
Check Out More Resources:
Articles:
Website: https://laravelplug.com/
YouTube Channel: https://www.youtube.com/channel/UCnTxncHQcBSNs4RCuhWgF-A?sub_confirmation=1
WordPress Playlist: https://www.youtube.com/watch?v=8VvXzFAFwQU&list=PLVoVZqAh8dTLHZ51egvEU7dsOrRCSIMWx
Tools Playlist: https://www.youtube.com/watch?v=gTQoUn3BQkM&list=PLVoVZqAh8dTK-DWHBGWOEEvzvPQrgFne-
WordPress Tutorials: https://laravelplug.com/category/wordpress/
Laravel Tutorials: https://laravelplug.com/category/laravel/
PHP Tutorials: https://laravelplug.com/category/php/
SQL Tutorials: https://laravelplug.com/category/sql/
Various Tips: https://laravelplug.com/category/tips/
Useful Tools: https://laravelplug.com/category/tools/
Socials:
Twitter: https://twitter.com/LaravelPlug
Pinterest: https://www.pinterest.com/LaravelPlugCom/
Facebook: https://www.facebook.com/groups/1020759861842360
Mail: info@laravelplug.com
#laravel #guide #php