Method – Add Two numbers

This tutorial is using the same base code as Add two numbers, but with using the function addtwo, this takes two parameters $a and $b which are both set to 0 as the default value and returns the two values added together. The answer part of the web page uses the function to add the two numbers together.

The source code

<?php
       function addtwo($a = 0, $b = 0)
       {
              return ($a + $b);
       }
       $value1 = $_POST['value1'];
       $value2 = $_POST['value2'];
?>
<html>
       <title>PHP - Add two numbers</title>
       <body>
              <form action="addtwonumbers.php" method="post">
                     <input type="text" name="value1" value="0" />
                     <input type="text" name="value2" value="0" />
                     <input type="submit" value="Calculate values"/>
              </form>
              Answer : <?php echo addtwo($value1+$value2); ?>
       </body>
</html>

save as addtwonumbers_function.php, this program will function the same as the previous tutorial apart from the inner working will call the method. The method programming allows for one method to be called multiple times, e.g. Within the example above there could be a method that was 5 lines in length and instead of writing the same 5 lines each time, you just write a method that is called.

4 thoughts on “Method – Add Two numbers”

  1. Well spotted Tom, I copy and pasted from the previous tutorial and forgot to alter the parameters to the function.. It was

    Answer :

  2. $value1 = $_POST[‘value1’];
    $value2 = $_POST[‘value2’];

    Errors:
    Notice: Undefined index: value1 in D:\PHP\EasyPHP 3.0\www\test.php on line 14

    Notice: Undefined index: value2 in D:\PHP\EasyPHP 3.0\www\test.php on line 15

Leave a Reply

Your email address will not be published. Required fields are marked *