Welcome!

By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!

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

New member
Joined
Feb 14, 2023
Messages
4
The pre-increment in the IF statement has no effect. Can anyone please explain?

Code:
<?php 
     $x = 10;
     if($x < ++$x) 
     { 
       echo "Hello World"; 
     }   
?>
 
New member
Joined
Feb 14, 2023
Messages
6
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.

Code:
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:

Code:
<?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:

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