In this PHP program, we will find the largest number among three numbers provided by the user. The program will take three integer inputs, compare them, and display the largest number.
Explanation
We will ask the user to input three numbers and use conditional statements (if-else
) to compare them. The logic for determining the largest number is as follows:
- First, we compare if
num1
is greater than bothnum2
andnum3
. If true,num1
is the largest. - If
num1
is not the largest, we check ifnum2
is greater thannum3
andnum1
. If true,num2
is the largest. - If neither of the above conditions are true, then
num3
must be the largest.
PHP Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | <html> <head> <title>PHP Test</title> </head> <body> <form method="post"> First Number: <input type="text" name="num1"><br> Second Number: <input type="text" name="num2"><br> Third Number: <input type="text" name="num3"><br> <input type="submit" value="Find Largest" name="find"> </form> <?php // Check if the form is submitted if(isset($_POST["find"])) { // Get the values entered by the user $num1 = $_POST["num1"]; $num2 = $_POST["num2"]; $num3 = $_POST["num3"]; // Compare the three numbers to find the largest if($num1 > $num2 && $num1 > $num3) { echo $num1." is the largest among the three numbers."; } else if($num2 > $num3) { echo $num2." is the largest among the three numbers."; } else { echo $num3." is the largest among the three numbers."; } } ?> </body> </html> |
Explanation of the Code:
- HTML Form:
- The user is prompted to enter three numbers in the form fields (
num1
,num2
, andnum3
). - When the user clicks the “Find Largest” button, the form submits the data to the PHP script.
- The user is prompted to enter three numbers in the form fields (
- PHP Logic:
- The
isset()
function checks if the form is submitted. - The values of
num1
,num2
, andnum3
are fetched using$_POST
. - The conditional statements (
if-else
) compare the values to determine the largest number.
- The
- Output:
- Depending on the condition, the largest number is printed.
Example of Output:
If the user enters the numbers:
num1 = 20
,num2 = 15
,num3 = 25
1 2 3 | 25 is the largest among the three numbers. |
If the user enters the numbers:
num1 = 12
,num2 = 25
,num3 = 18
The output will be:
1 2 3 | 25 is the largest among the three numbers. |
Conclusion
This simple PHP program demonstrates how to compare numbers and determine the largest one. By using a basic HTML form and PHP conditional statements, you can easily create such programs to interact with users and display the results based on their inputs.