Operators in PHP are some character(s) or symbols which are used to perform some tasks on provided values or variables.
For example “4+2 = 6”, in this expression 4 and 2 are values and + is operator which adds 4 and 2 and then gives 6 as a result.
Similar to other programming languages, operators in PHP are divided on various categories based on the type of operations they perform. Operators in PHP are divided into following groups –
– Arithmetic Operators
– Assignment Operators
– Comparison Operators
– Increment/Decrements Operators
– Logical operators
– String Operators
– Array Operators
– Conditional Operators
Arithmetic Operators
Arithmetic operators in PHP, like any other programming language are used to perform simple mathematical operations like addition, subtraction, product etc. Following table show arithmetic operators available in php –
Operator | Name | Usage | Action |
+ | Addition | $a + $b | Adds values of a and b. |
– | Subtraction | $a – $b | Subtracts the value of b from a |
* | Multiplication | $a * $b | Product of the values of a and b |
/ | Division | $a/$b | Provides the quotient when a is divided by b |
** | Exponentiation | $a ** $b | a raised to the power b |
% | Modulus | $a % $b | Provides the remainder when a is divided by b |
Assignment Operators in PHP
Assignment operators are used to write a value to the variable. Generally, the values on the right of expression are set to the left of the expression –
Following are assignment operators used in PHP –
Operator | Name | Usage | Action |
= | Assign | $a = $y | Stores the value of y in a |
+= | Add then assign | $a+=$b | a is added to b and then stored in a. It is equivalent to$a = $a+$b; |
– = | Subtract then assign | $a-=$b | Equivalent to $a=$a-$b |
*= | Product then assign | $a *= $b | Similar to $a = $a*$b |
/= | Divide and assign | $a /= $b | $a = $a/$b |
%= | Divide and assign (remainder) | $a%=%b | $a=$a%$b |
Comparison Operators
Comparison operators in PHP, like any other language, compares both sides of the expression and provides Boolean (true or false) results based on the operator used-
Following table shows comparison operators in php –
Operator | Name | Usage | Action |
== | Equal | $a == $b | Returns true if a is equal to b |
=== | Identical | $a===$b | Return true if a is equal to b and both have same data-type |
!= | Not Equal | $a!=$b | Returns true if a is not equal to b |
!== | Not Identical | $a!==$b | Return true if a is not equal to b or they are not of same type |
> | Greater than | $a>$b | Return true if value of a is greater than b |
< | Less than | $a<$b | Return true if a is less than b |
>= | Greater than or equal to | $a>=$b | Returns true if a is greater than or equal to b |
<= | Less than or equal to | $a<=$b | Returns true if a is less than or equal to b |
<=> | Spaceship | $a<=>$b | Returns -1 if a is less than b, 0 if both are equal and 1 if b is less than a |