Introducing Operators

In the previous section you learned about variables, data type, and constant and how to declare them. However, to use or declare variables or constants you need operators. The fallowing problem and its solution explain the use of operators.

Identify the operators to be used

Operators are an integral part of any programming language, they are symbol that represent a specific action. For an example, the plus sign indicates that addition needs to be performed and is an operator use for addition. Using operators, you can perform a number of operation on a variable:
 - Assign a value to a variable
 - Change the value of a variable
 - Compare two or more values
 - Specify a condition

There are 6 basic operator categories:

 - Arithmetic Operator
 - Assignment Operator
 - Comparison Operator
 - Increment/decrement Operator
 - String Operator
 - Logical Operator

Arithmetic operators

Arithmetic operators are used to perform elementary mathematical calculation and are used when value of variable declare in integer type.
Name Example Output
Addition $a+$b The sum of $a and $b
Subtraction $a-$b The difference between $a and $b
Multiplication $a*$b The product of $a and $b
Division $a/$b The quotient of $a and $b
Modules $a%$b The remainder after dividing $a and $b

Let us look at some examples for a better understanding of arithmetic operators:


$a = 3;
$b = 6;
$c = $a+$b ; // The value of $c is now 9.


$a = 11;
$b = 2; $c = $a-$b; //The value of $c is now 9.


$a = 3;
$b = 3;
$c = $a*$b; //The value of $c is now 9.


$a = 18;
$b = 2;
$c = $a/$b ; //The value of $c is 9.


$a = 9;
$b = 3;
$c = $a%$b; //The value of $c is now 0.

Assignment Operators

Assignment operators are use to assign a specific value to variable. They are also use to change the existing value of a variable by adding or subtracting from the variable 's current value. A few examples are =, +=, -= and .=.
In PHP you can use more than one assignment operator in a single statement, as shown below:

 $a = ($b=4) + ($c=5);

The variable $a, $b and $c are now integer types and will hold the values 9, 4 and 5, respectively.
Operator Usage Output
= (equal to) $a = 9; Assign value 9 to variable $a;
+= (plus equal to) $a += 9; Adds the original value assign to the variable $a to 9. Now the value of $a will be 9.
-= (minus equal to) $a += 3; Subtract the number specified from the original value of $a. Now the value of $a will be 6.
.= (dot equal to) $a .=" new numbers."; (add) the new value specified with the original value of the variable. Now the value of $a will be 9 new numbers.

comments powered by Disqus