PHP operator precedence

precedence  :  operator precedence determines the order in which operators are evaluated. operators with higher precedence are evaluated first.

or

operator precedence refers to the order in which operators execute within an expression.

                  5 + 5 * 5    //   returns   value   30

in above statement multiplication operator ('*') has higher precedence than the addition operator ('+') and thus will be evaluated first.

associativity essentially means the 'direction' in which an expression containing an operator is evaluated.the direction can be   left-to-right   or   right-to-left  .


the following table lists the PHP operators, ordered from highest to lowest precedence.

operatorprecedenceassociativity
new  0(highest)  non-associative
clone
[  1  left to right
++  2  right to left
--
~
(type)
@
instanceof  3  non-associative
!  4  right to left
*, /, %  5  left to right
+, -, .  6
>>  7
<<
>  8  non-associative
<
>=
<=
==  9
===
!=
!==
<>
&  10  left to right
^  11
|  12
&&  13
||  14
? :  15
=,   *=,   /=,   %=,

+=,   -=,   .=,   &=,   ^=,

|=,   <<=,  >>=,   =>
  16  right to left
and  17  left to right
xor  18
or  19
,  20(lowest)  left to right

note : expressions within parentheses () are evaluated first.

                2 + 4 * 5           //  result    value   is  22
                ( 2 + 4 ) * 5         //result      value   is 30 

  

PHP operator precedence examples

   <?php
                $x = 4; $y = 5;
                
                $result = $x++ + ++$x / --$y * --$y; // please solve this equation
                
                echo  "x value = {$x} <br/>";
                
                echo  "y value = {$y} <br/>";
                
                echo  "result = {$result} <br/>";   
   ?>

 

 <?php
     
 $a = 2; $b = 8; $c = 8;
                      
 $result = ($a * $a <= $b * $a) && (--$a * $a-- !== ++$b - --$c);// please solve it
                      
       echo  "after complete the above statement a value = {$a} <br/>";
                      
       echo  "after complete the above statement b value = {$b} <br/>";
                      
       echo  "after complete the above statement c value = {$c} <br/>";
                      
       var_dump($result);
?>

 

   <?php
   
               $x  = "sandeep " ."kumar" . 100 * 20 ;
               
               $y  = "ram " . "kumar " . "dhaka " . 12 * 12;
               
               $z  = "vinod ";
               
               $z .= $x;
               
               
               var_dump($x);
               
               var_dump($y);
 
               var_dump($z);
  ?>