Learning PHP: Some Basic Math

19 Feb

Welcome back!

The next step we’re going to take with PHP is to get it performing some basic math operations for us. PHP easily makes short work of even the most complicated math work, but you need to know how to write it.

The example below will step you through the basic operations in math.

Try them out for yourself and see how you get on!

<?php

// First we are going to set up some variables with values.

$value1 = 10;
$value2 = 5;

// Now we're going to explain the various ways we can do math.

// Multiplication Example: 10 X 5 is done in PHP using the asterisk *

$multiplication = $value1 * $value2; // 10 x 5

// Addition is done using the plus sign

$addition = $value1 + $value2; // 10 + 5

// Division is done using a forward slash

$division = $value1 / $value2; // 10 / 5

// Subtraction is done using a hyphen

$subtraction = $value1 - $value2; // 10 - 5

// Brackets

// We can also use brackets in our math.

$brackets = ($value1 + $value2) + ($value1 - $value2); // (15) + (5)

// Now we can print out our results

echo $multiplication;

echo '<br /><br />'; // This is used to add a couple of line breaks so that the output doesn't run into itself. Try removing these and see what happens

echo $addition;

echo '<br /><br />'; // This is used to add a couple of line breaks so that the output doesn't run into itself. Try removing these and see what happens

echo $division;

echo '<br /><br />'; // This is used to add a couple of line breaks so that the output doesn't run into itself. Try removing these and see what happens

echo $subtraction;

echo '<br /><br />'; // This is used to add a couple of line breaks so that the output doesn't run into itself. Try removing these and see what happens

echo $brackets; // This is the last line so no need to add the breaks.

If you have any questions, please leave a comment below and I’ll get you sorted out!