Arithmetic Operators in PHP
PHP Operators – Part 2
Forward: In this part of the series we look at Arithmetic Operators in PHP.
By: Chrysanthus Date Published: 10 Aug 2012
Introduction
Note: If you cannot see the code or if you think anything is missing (broken link, image absent), just contact me at forchatrans@yahoo.com. That is, contact me for the slightest problem you have about what you are reading.
Addition Operator
Read and try the following code. The explanation is given below.
<?php
$id1 = 20;
$id2 = 30;
$id3 = $id2 + $id1;
echo $id3;
?>
20 is kept in a region in memory identified by $id1. 30 is kept in the region identified by $id2. In the third statement, PHP takes the content of $id2 and adds it to the content of $id1, then it puts the result as content for the region of the newly declared identifier (variable), id3. This addition is done without affecting or changing the contents of $id2 and $id1.
Subtraction Operator
Read and try the following code. The explanation is given below.
Code example:
<?php
$id1 = 20;
$id2 = 30;
$id3 = $id2 - $id1;
echo $id3;
?>
The explanation is similar to the previous case, but this time, subtraction is done.
Read and try the following code. The explanation is given below.
<?php
$id1 = 20;
$id2 = 30;
$id3 = $id2 * $id1;
echo $id3;
?>
Note that the multiplication operator is * and not X. Here * is the multiplication operator and not the dereference operator. * multiplies two numbers.
Division Operator
Read and try the following code. The explanation is given below.
Code example:
<?php
$id1 = 3;
$id2 = 15;
$id3 = $id2 / $id1;
echo $id3;
?>
Note that the division operator is, / . 3 is kept in the object identified by id1. / divides two numbers.
The modulus operator divides the first operand by the second operand and returns the remainder. Read and try the following code:
<?php
$id1 = 17;
$id2 = 12;
$id3 = $id1 % $id2;
echo $id3;
?>
The Modulus operator is the percentage sign.
The – Operator
This is the negation operator. If the value of the operand is a positive number, it changes it to a negative number. If it is a negative number, it changes it to a positive number. This same symbol is used for subtraction, but here it is a negation operator. The following example illustrates this:
<?php
$int1 = +5;
$int2 = -6;
$intA = -$int1;
$intB = -$int2;
echo $intA . "<br />";
echo $intB;
?>
If you try the above code, the value of $intA will be –5 and the value of $intB will be +6 (same as 6).
So there are 6 arithmetic operators that are:
+ - * / % negation
Arithmetic operators operate from left to right; that is from the left operand to the right operand.
That is it for arithmetic operators. We take a break here and continue in the next part of the series.
Chrys
Related Links
Major in Website DesignWeb Development Course
HTML Course
CSS Course
ECMAScript Course
NEXT