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

OperatorsAdditional InformationAssociativity
[array()left
**arithmeticright
++ -- ~ increment/decrement and typesright
instanceotypesnon-associative
!logical (negation)right
* / %arithmetiarithmeti
+ - .arithmetic and string concatenationleft
<< >>bitwise (shift)left
< <= > >=comparisonnon-associative
!ERROR! A11 -> Formula Error: Unexpected operator '='comparisonnon-associative
&bitwise ANDleft
^bitwise XORleft
|bitwise ORleft
&&logical ANDleft
||logical ORleft
?:ternaryleft
!ERROR! A18 -> Formula Error: Unexpected operator '='assignment right
andlogicalleft
xorlogicalleft
orlogicalleft
,many uses (comma) left

Question and Answer-

  •  What will be the output of the following PHP code?
<?php
$a = 10;
$b = 12;
$c= $a + $b;
$c= 22;
?>

Output: 22

  • What will be the output of the following PHP code?
<?php
$x = "test";
$y = "this";
$z = "also"; 
$x .= $y .= $z ;
echo $x;
echo $y;
?>

Finally Output: testthisalsothisalso

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?
<?php
$x = 1;
$y = 2;
if (++$x == $y++)
{
    echo "true ", $y, $x;
}
?>

Output: true 23

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?
<?php
$y = 4;
if ($y-- == ++$y)
{
    echo $y;
}
?>

Output:

4

Explanation: First $y = 4 is compared to and then decremented, then incremented and compared to $y = 4