Home > Article > Backend Development > PHP analysis on $i++ and ++$i
This article uses the VLD tool to analyze the opcode of php to explain the reason. First, post the picture
T1.php code
$i = 1;
$i+$i++;
Vld code
number of ops: 5
compiled vars: !0 = $i
line # * op fetch ext return operands
------------------------- -------------------------------------------------- --------
2 0 > ASSIGN ~2 gt ; RETURN 4
path #1: 0,
T2.php code
$i = 1;
$i+$i+$i++
Vld2 code
number of ops: 6
compiled vars: !0 = $i
line # * op fetch ext return operands
--------- -------------------------------------------------- -----------------------
2 0 > ASSIGN
2 POST_INC 3 ADD ~3
4 5 > RETURN 2- 4; sop: 0 ; eop: 5
path #1: 0,
Let’s compare the two pictures 2 and 4, and you can know why the results will surprise you
First analyze the execution results of 1 and 2
First $ i is assigned a value of 1, $i++ is incremented, the result 1 is copied to the temporary variable ~1 ($i), and then $i is incremented to 2, that is! 0=2, of course the final result ~2 = ~1+! 0 ===3;
Let’s analyze 3,4
First, $i is assigned a value of 1, then $i+$i = !0+!0 == ~1 == 2, then $i++ is incremented, and The result 1 is copied to the temporary variable ~2 ($i), and the final result ~1+~2 == 2+1 ===3;