Search code examples
phpif-statementincrement

Pre Increment in the IF statement has no effect. Why?


The pre-increment in the IF statement has no effect. Can anyone please explain?

<?php  
     $x = 10; 
     if($x < ++$x)  
     {  
       echo "Hello World";  
     }   
?> 

Solution

  • As shown by the opcode dump below, and it shows:

    1. $x is assigned value 10
    2. $x is then incremented to 11 at the memory location
    3. if is executed

    Therefore, when you are making the if you are effectivelly comparing variables (memory location) $x with $x and not values 10 and 11.

    line      #* E I O op                           fetch          ext  return  operands
    -------------------------------------------------------------------------------------
        2     0  E >   ASSIGN                                                   !0, 10
        3     1        PRE_INC                                          ~2      !0
              2        IS_SMALLER                                               !0, ~2
              3      > JMPZ                                                     ~3, ->5
        5     4    >   ECHO                                                     'Hello+World'
        7     5    > > RETURN                                                   1
    

    What your code does, is really the following:

    <?php
    $x=10;
    ++$x;
    if ($x < $x){
    

    The order of evaluation of the operands seems not guaranteed inside a if block, which means the value of $x may be incremented as you seem to expect, or at some other time. the pre_increment has a not well defined behavior.

    To fix this, use the increment, it has a very well defined behavior:

    <?php
    $x = 10;
    if ($x < $x++){
    echo "hello world";
    }
    

    I say the pre_inc behavior is not well defined, because it varies from php interpreter to interpreter. Here's an example of the code that works "as you'd think is expected": https://3v4l.org/n0v6n#v5.0.5

    and here's how it "fails": https://3v4l.org/n0v6n#v7.0.25