Let’s see a basic PHP Program for Beginners. Today we will write a Factorial Program in PHP to find the factorial of a number inputted by the user. Here we will make two files – One to take input and other to calculate factorial and show the output.
First File – Factorial.html
Here simply use HTML to make a form with one textbox and one submit button that’s it. Put method Get and set action=”YOUR_OTHER_FILE_NAME”. Here our other PHP file is named as “facto.php” so we have written that. That’s it for your HTML File. Now you can take input from the user to calculate factorial of any number.
<form name=”frm1″ method=”get” action=”facto.php”>
<input type=”text” name=”num” placeholder=”Enter Number”>
Second File for Factorial Program – facto.php
In the second file, we will write the code to calculate the factorial. We stored the User Inputted number in our Variable $no and stored 1 in $fact variable. We used _GET associative array to store number inputted by the user because we used GET method in our first file. Then, You need to know how factorials are calculated. Example: Factorial of 5 is calculated like this: 5*4*3*2*1
We are looping in reverse down in here( That is: 1*2*3*4*5 manner). The loop starts from 1, goes till $no and increments after every iteration. Then we simply multiply $fact with $i each time and store it in $fact. That’s it. Just print the $fact variable and you have your Factorial with you. See the processing below and you will understand.
echo “THE FACTORIAL OF $no IS $fact “;
We are making a long series of PHP Programs for beginners, do follow us to keep learning more. If you liked this article and learnt the Factorial Program in PHP then please share this article on any social media. Keep Learning, Keep Coding.