How To Generate Random Number In PHP
Last Updated : Jul 1, 2023
In this tutorial we will show you the solution of how to generate random number in PHP, in our last php tutorial, we understand about creation of php file, html in php code, and many other things.
In this tutorial to generate random function we are going to use rand() function.
This is php inbuilt function and used to generate a random number in php.
The rand() function has been an alias of the mt_rand() function. And we are also able to pass parameters inside this.
Step By Step Guide On How To Generate Random Number In PHP :-
<!DOCTYPE html> <html> <head> <title> php rand() function </title> </head> <body> <h1> here under is our php code </h1> <?php echo(rand() . "<br>"); echo(rand() . "<br>"); echo(rand(10,100).”<br>”); echo(rand(10,100).”<br>”); echo(rand(100,1000)); ?> </body> </html>
- First, we write <! DOCTYPE html> which we used as an instruction to the web browser about what version of HTML file is written in and we use php inside body of html.
- Secondly, the <html> tag is used to indicate the beginning of an HTML document.
- As above now <head> tag is used to contain information about web page. In this tag a <title> tag is used which helps us to specify a webpage title. Both <head> and <title> tags are Paired tags. So, both have </head> and </title> ending tags respectively.
- Thirdly, <body> tag is used to define the webpage body. All the contents to show on website are written here.
- Here, we create a heading tag with help of html tags. And rest is code inside of body is written under php tags.
- Now, here we create a basic structure of php by opening and closing php codes that are <?php ?>. All the php content is always written inside these codes.
- Here, we use echo five times and first two and next two are same. This is to show you that when you run this code. Php always generate different number in most of cases.
- For random numbers we use here rand() function. You can also able to give limit of number by passing parameters like rand(0,100). Now, it always generates random number between 0 to 100.
- There are mainly two parameters of rand() function. One from them is minimum and other one is maximum. You can see the rand() function with parameters in our example.
- At last, the <body> and <html> tags are closed with </body> and </html> respectively.
At last in conclusion, here we can say that with the help of this article we are able to generate a random number in php. I hope this tutorial on how to generate random number in PHP helps you.