Tutorials – Addition in PHP

basic_maths

OK, let’s do some adding up. To add up in PHP, the plus symbol (+) is used. (If you still have the code open from the previous page, try changing the full stop to a plus symbol. Run the code, and see what happens.)

To add up the contents of variables, you just separate each variable name with a plus symbol. Try this new script:

<?php

$first_number = 10;
$second_number = 20;
$sum_total = $first_number + $second_number;

$direct_text = ‘The two variables added together = ‘;

print ($direct_text . $sum_total);

?>

In the above script, we’ve added a second number, and assigned a value to it:

$second_number = 20;

basic_mathsA third variable is then declared, which we’ve called $sum_total. To the right of the equals sign, we’ve added up the contents of the first variable and the contents of the second variable:

$sum_total = $first_number + $second_number;

PHP knows what is inside of the variables called $first_number and $second_number, because we’ve just told it in the two line above! It sees the plus symbol, then adds the two values together. It puts the answer to the addition in the variable to the left of the equals sign (=), the one we’ve called $sum_total.

To print out the answer, we’ve used concatenation:

print ($direct_text . $sum_total);

This script is a little more complicated than the ones you’ve been doing. If you’re a bit puzzled, just remember what it is we’re doing: adding the contents of one variable to the contents of another. The important line is this one:

$sum_total = $first_number + $second_number;

The addition to the right of the equals sign gets calculated first ($first_number + $second_number). The total of the addition is then stored in the variable to the left of the equals sign ($sum_total =).

You can, of course, add up more than two numbers. Try this exercise.
Exercise
Add a third variable to your code. Assign a value of 30 to your new variable. Put the sum total of all three variables into the variable called $sum_total. Use concatenation to display the results. (In other words, add up 10, 20, and 30!)
You don’t have to use variable names to add up. You can do this:

print (10 + 20 + 30);

Or even this:

$number = 10;

print ($number + 30);

But the point is the same – use the plus symbol (+) to add up.

 
Download the PHP Course Files

From http://www.homeandlearn.co.uk