How to add two numbers using PHP

Friday, July 29, 2011 · Posted in ,

In this tutorial, we will know how to add two numbers using PHP. PHP can also perform arithmetic and can be use to solve mathematical equations. Sample problem is the given problem below which ask the user to input two numbers and get the sum of the two numbers.

Problem:
Write a program that will ask the user to input to numbers. Then the program must computer the sum of the two numbers and display.

Code:
<html>
<head>
<title>Title goes here</title>
</head>
<body>

<form action="" method="post">
<label>Enter Num1:</label>
<input type="text" name="num1" /><br>
<label>Enter Num2:</label>
<input type="text" name="num2" /><br><br>
<input type="submit" name="btn_submit" value="Add">
</form>

<?php
if(isset($_POST['btn_submit']))
{
$num1 = $_POST['num1'];
$num2 = $_POST['num2'];

$total = $num1+$num2;

echo "The total value is: ".$total;
}
?>


</body>
</html>
Explanation:

The program allow the user to input two numbers as stated on the problem above. The program provide user to input field which has a name of num1 and num2. When the user click the submit button the program will going to execute the PHP scripts below. PHP script first execute the condition if to determine whether the use had click the button or none. When the condition returns true then the following lines of code will be execute. The value from the form text field that has a name of num1 and num2 will be stored in a temporary variable which is the $num1 and $num2. Then, the next line of code wil be executed in which perform the adding of the two numbers and stored the sum in the variable named $total. To finish with the last line of script will be executed which display the total of the two numbers adn we use the variable total which contains the sum value of the two numbers. Below is the sample output from the given codes above.

Sample Output:

If there are some comments or questions about this article just CLICK THIS LINK to be redirected to the forum page.



» More Articles can be found in this site. Click Here

5 Responses to “How to add two numbers using PHP”

Unknown said...

Well, Thanks for giving this code. I was searching the code for adding tow numbers in PHP. Really you have given greater efforts for writing it.

indesign training sydney

Anonymous said...

It is Helpful !!!

Thankxx

Unknown said...

Tnx for help!
Write more articles about php...
I Wish may u can more & more about php!!!

Unknown said...

helpful code, but why use . in adding

Unknown said...

I want to know how can i display sum in 3rd text input type.

Powered by Blogger.