Introduction to PHP – Part 3

advertisement

Operators

An operator is a type of function which acts on operands often called inputs and produce results. In PHP, there are three types of operators. Increment operator ++ and decrement operator — belongs to the first operator group called unary operator. Unary operator always acts on single operand. The second group called the binary operator acts on more than two operands. .The group is the ternary operator : ? :. This operator is used to select between two expressions depending upon the third one. These operators can be classified in the following ways based on the type of functionality they provides.

Arithmetic Operators

Operator Operation Example Result
++ Increment x=6
x++Here, x is called operand
x=7
Decrement x=2
x–
x=1
+ Addition 1+1 2
- Subtraction 2-1 1
* Multiplication 2*3 6
/ Division 3/2 1.5
% Modulus 3%2
5%3
6%2
1
2
0 We can notice that result is division remainder

Assignment Operators

Operator Example Assuming x=10 and y=5
= x=y x will be 5
+= x+=y Equivalent to x=x+y, hence x will be 15
-= x-=y Equivalent to x=x-y, hence x will be 5
*= x*=y Equivalent to x=x*y, hence x will be 50
/= x/=y Equivalent to x=x/y, hence x will be 2
.= x.=y Equivalent to x=x.y, hence x will be 105. More clearly, if x=23 and y =11, then x will be 2311
%= x%=y Equivalent to x=x%y, hence x will be 0

Comparison Operators

Operator Operation Returns TRUE if Returns FALSE if
== is equal to 2==2 1==2
!= is not equal 1!=2 2!=2
is greater than 2>1 1>2
is less than 1<2 2<1
>= is greater than or equal to 2>=1, 2>=2 1>=2
<= is less than or equal to 1<=2, 2<=2 2<=1

Logical Operators

Operator Operation Returns TRUE if Returns FALSE if
&& ANDReturns true only if the both expressions are true (2==2 && 1<2) (2==2 && 1>2)
|| ORReturns true if one of the expressions is true (2==2 || 1>2) (2!=2 ||1>2)
! NOTComplement the result of an expression !(2==3) !(2==2)

Operators Precedence and Associativity

The precedence of an operator specifies which operation is carried first. For example, the result of 2+5*2 is 12 not 14. Here multiplication is evaluated first followed by addition, hence, we say that operator “*” has higher precedence than operator “+”. In some cases parenthesis is used to force the precedence. For instance, the result from same expression with parenthesis like (2+5)*2 will produce result 14.

Associativity decides the order of evaluation of an expression if the operators have equal precedence. If a expression is evaluated from right we called right associativity and for left we say left associativity. The following table shows the precedence of operators having highest precedence. Operators having same associativity are listed in the same line. 

Operators
++ –
!
* / %
+ -
<< >>
< <= > >=

About the Author:

Bhoj R Dhakal is a programmer. He has few years of experience in software development and maintenance. He has published series of PHP tutorials for webanddesigners.

Other News