Articles

Learn about PHP operators

PHP operators Lesson 5 Tutorials PHP

5. Using basic operators to perform calculations on variables and values

5. Using basic operators to perform calculations on variables and values.

In the last example we left off by using the plus symbol to add integers together. In addition to using the plus operator you can use minus, multiplication, division and percentage symbols.

PHP Code example

$anumber = 20;
$bnumber = 15;
echo $anumber + $bnumber;

PHP output display

35

Using additional operators like +,-,*,/,% to perform calculations.

PHP Code example

$anumber = 2;
$bnumber = 4;
echo $anumber + $bnumber; /// would equal 6
echo $anumber - $bnumber; /// would equal -2
echo $anumber * $bnumber; /// would equal 8
echo $bnumber / $anumber; /// would equal 2
echo $bnumber % $anumber; /// would equal 0

You can also perform more complex calculations by bracketing values.

echo ($anumber + $bnumber)*2; /// would equal 12 (2+4)*2 = 12

Shortening the operators can improve code production.

$a += 1; is equivalent to $a=$a+1;
$a -= 1; is equivalent to $a=$a-1;
$a *= 1; is equivalent to $a=$a*1;
$a /= 1; is equivalent to $a=$a/1;

***
Do Not Sell My Personal Information