Operators in PHP
All the valid operators are available in PHP just like any other language. A list of operators is given below.
| Operator | Description | Example |
|---|---|---|
| + | Addition | if x=1, x+2 will be 3 |
| - | Sutraction | if x=2, x-2 will be 0 |
| * | Multiplication | if x=2, x*2 will be 2 |
| / | Division | if x=2, x/2 will be 1 |
| ++ | Increment | if x=1 x++ will be 2 |
| -- | Decrement | if x=2, x-- will be 1 |
| += | Set RHS + LHS to LHS | if x=2, x+=3 will set the value of 5 in x. Similary other operatos like -=, *=, /= and .= etc. |
Logical operators when evaluated, return a boolean value.i.e true or false. For Example, if x=2 and y=3 then the expression x>y will evaluate to be false. These operators are mostly used in looping and conditional processing. We will very soon learn these topics.
| Operator | Description | Example |
|---|---|---|
| > | Greater than | if x=1, x>2 will return false (0) |
| < | Less than | if x=1, x<2 will return true (1) |
| >= | Greater than or Equal to | if x=1, x>=1 will return true (1) |
| <= | Less than or Equal to | if x=1, x<=2 will return true (1) |
| != | Not Equal to | if x=1, x!=2 will return true (1) |
The following example will clarify these concepts.
Example
| The PHP Code | Output of this code |
|---|---|
<?php $x = 2; $y = 3; echo "$x > $y = ".($x>$y)."<br>"; echo "$x<$y\ = ".($x<$y)."<br>"; echo "$x!=$y = ".($x!=$y)."<br>"; echo "$x>=$y = "($x>=$y)."<br>"; ?> |
$x>$y = $x<$y = 1 $x!=$y = 1 $x>=$y = |
Notice the output of this code. The print function echo does not print null or false values. However it prints the "true" value as 1.
Boolean operators are used to join two logical expressions. The resulting joined expression returns true or false depending on the values of the individually joined expressions and the boolean operator. This will be clarified with an example.
| Operator | Description | More Description |
|---|---|---|
| && | AND | Expression joined by this operator return true only if the individual expression evaluate to true. In all other conditions, it returns false. |
| || | OR | Expression joined by OR operator returns false only if all the individual expressions also evaluate to false. In all other conditions, it returns true. |
| ! | NOT | Negates an expression. True becomes false and false becomes true. |
- 585 reads
