PHP Tutorial 3
By James Moran
Performing calculations
So far we have just be playing with text, but PHP is so much more powerful than that. One of PHP's main features is its ability to perform calculations.
Lets get straight into it then. Create your file called program4.php and add the arrow question marks.
Create variables called number1, number2 and percentage. Give number1 the value of 15, number2 the value of 4 and percentage the value of 17.5. Now create a variable called total_net. To add the variables together just write
$total_net = $number1 + $number2;
So now the variable total_net contains the result from the calculation. Create another variable called total_gross and perform another calculation which should read.
$total_gross = ( $total_net * ( $percentage / 100 ) ) + $total_net;
PHP uses all the normal standard calculation operators + (plus), - (minus), * (times) and / (divide). Separate mini calculations inline using brackets.
Now echo all the data.
echo 'First Number: '.$number1;
echo '<br />Second Number: ' .$number2;
echo '<br />Total Net: ' .$total_net;
echo '<br />Total Gross: ' .$total_gross;
The whole program should read
<?
$number1=15;
$number2=4;
$percentage=17.5;
$total_net = $number1 + $number2;
$total_gross = ( $total_net * ( $percentage / 100 ) ) + $total_net;
echo 'First Number: '.$number1;
echo '<br />Second Number: ' .$number2;
echo '<br />Total Net: ' .$total_net;
echo '<br />Total Gross: ' .$total_gross;
?>
Save, upload and view the file. It should read
First Number: 15
Second Number: 4
Total Net:19
Total Gross: 22.325
PHP can perform much more complex mathematical calculations but I'm rubbish at maths so this is as far as this section goes.
That's it for tutorial 3, have another cookie.