PHP Operators
PHP Operators is a symbol which used to perform operations on operands.
$num=14+16;
Explanation:
Here + is the operator and 14,16 are operands $num is variable
PHP Operators Types:
- Assignment Operators
- Arithmetic Operators
- Array Operators
- Bitwise Operators
- Comparison Operators
- Logical Operators
- String Operators
- Incrementing/Decrementing Operators
- Type Operators
- Execution Operators
- Error Control Operators
We can also categorize operators on behalf of operands.
Binary Operators: works on two operands such as binary +, -, *, / etc.
Unary Operators: works on single operands such as ++, — etc.
Ternary Operators: works on three operands such as “?:”.
PHP Operators Precedence
| Operators | Additional Information | Associativity |
|---|---|---|
| [ | array() | left |
| ** | arithmetic | right |
| ++ -- ~ | increment/decrement and types | right |
| instanceo | types | non-associative |
| ! | logical (negation) | right |
| * / % | arithmeti | arithmeti |
| + - . | arithmetic and string concatenation | left |
| << >> | bitwise (shift) | left |
| < <= > >= | comparison | non-associative |
| !ERROR! A11 -> Formula Error: Unexpected operator '=' | comparison | non-associative |
| & | bitwise AND | left |
| ^ | bitwise XOR | left |
| | | bitwise OR | left |
| && | logical AND | left |
| || | logical OR | left |
| ?: | ternary | left |
| !ERROR! A18 -> Formula Error: Unexpected operator '=' | assignment | right |
| and | logical | left |
| xor | logical | left |
| or | logical | left |
| , | many uses (comma) | left |
Question and Answer-
- What will be the output of the following PHP code?
|
1 2 3 4 5 6 |
<?php $a = 10; $b = 12; $c= $a + $b; $c= 22; ?> |
- What will be the output of the following PHP code?
|
1 2 3 4 5 6 7 8 |
<?php $x = "test"; $y = "this"; $z = "also"; $x .= $y .= $z ; echo $x; echo $y; ?> |
Explanation: The x .= y is a shorthand for x = x.y and this is evaluated from right to left.
- What will be the output of the following PHP code?
|
1 2 3 4 5 6 7 8 |
<?php $x = 1; $y = 2; if (++$x == $y++) { echo "true ", $y, $x; } ?> |
Explanation: x is pre-incremented and y is post-incremented thus both are 2 in the if condition, later y is incremented.
- What will be the output of the following PHP code?
|
1 2 3 4 5 6 7 |
<?php $y = 4; if ($y-- == ++$y) { echo $y; } ?> |
|
1 |
4 |