Calculation with Variables

3 min read

In addition to texts or string, as shown in the first part, you can also store numbers in variables and calculate the result, for example, add, subtract or multiply them.

Basics

If one assigns a number to a variable, in contrast to the text or string, no quotation marks may be used. You write the number directly into your code.

<?php
$number1 = 10;
$number2 = 5;
echo "number1: $number1 <br />";
echo "Number2: $number2";
?>

The number 10 and 5 are now stored in these variables ($number1 and $number2).

The adding takes place using +. In the following script you define two numbers and store the sum of the two numbers in the variable $result:

<?php
$number1 = 10;
$number2 = 5;
$result = $number1 + $number2;
echo "Result: $result";
?>

For the calculation, the numbers do not necessarily have to be stored in variables. You can also write these directly into the mathematical expression. Subsequently, we save a number in the variable $number and add the value 5 to it.

<?php
$number = 1;
$result = $number + 5;
echo $result;
?>

Here are some more examples:

<?php
$number1 = 10;
$number2 = 5;
echo $number1 + $number2; // add
echo "<br />";
echo $number1 - $number2; // subtract
echo "<br />"; echo $number1 * $number2; // multiply
echo "<br />"; echo $number1 / $number2; // divide
echo "<br />";
echo pow($number1, $number2); // number1 raised to the power of number2 (10 ^ 5)
echo "<br />";
echo sqrt (64); // root of 64
echo "<br />";
echo 2 * $number1 + 5 * $number2 - 3; // calculate 2 * 10 + 5 * 5 - 3
?>
;

Of course, these results can also be saved again in extra variables.

Decrement and increment

To increase the value of a variable by 1 or to reduce it by 1, there is a simple trick:

<?php
$increase = 1;
$increase ++;
echo $increase;
?>

You can also lowering a number by placing double minus sign (--) in front of the variables:

<?php
$lower = 2;
$lower--;
echo $lower;
?>

If a double plus sign (++) is appended to the variable name (a number variable), the content of this variable, i.e., the number, is incremented, or increased by 1. On the other hand, if double minus signs (--) is used, the value is decremented, that is, decreased by 1.

Shorthand for assignments

The following script increases the value of defined variable by the number 10:

<?php
$number = 1;
$number = $number + 10;
echo $number;
?>

Since programmers always want the quickly one, PHP still has a shorthand that does exactly the same:

<?php
$number = 1;
$number += 10;
echo $number;
?>

+= Increases the value of the variable $num by the number 10. Of course, you can also write -=, *= or /= to subtract, multiply or divide values.

Floating point numbers

In PHP, you can also define a floating number by using a dot sign instead of commas. The mathematical operations remain the same.

<?php
$number1 = 2.5;
$number2 = 5.5;
$result = $number1 *
$number2;
echo "Result: $result";
?>

« »