Home > Back-end >  Unexpected behaviour of PHP when incrementing numbers in a statement
Unexpected behaviour of PHP when incrementing numbers in a statement

Time:11-22

Why is the result of this addition 9?

I expected it would be 8.

Why does PHP behave like this?

$n=3 ; 
$n=  $n     $n; 
echo $n;

CodePudding user response:

The two increments are done sequentially on the same variable, $n:

  • The first $n sets n from 3 to 4 and returns 4
  • The second $n sets n from 4 to 5 and returns 5

The result must be 9

CodePudding user response:

Looks natural, first pre-increment set $n = 4, and substitute first $n expression, then second pre-increment set $n = 5 (because it already was 4) and substitute second expression to 5, so we got 4 5

CodePudding user response:

Break the process down into separate variables and statements, and you'll more easily see why you get this result:

$n = 3; 
$x =   $n;
echo $x;
$y =   $n;
echo $y;
$z = $x   $y;
echo $z;

This will output

4
5
9

Why? Because the first $n increases $n by one, to 4. Then the next one increases it to 5.

In your example, you're doing exactly the same thing, but just all in one line. e.g. By the time PHP comes to evaluate the $n, $n is already 4, so after incrementing it again it becomes 5...and then obviously 4 5 = 9.

This shows you step by step how your original statement is evaluated by PHP:

$n = 3;
$n =   $n     $n;
$n =   3     $n;
$n = 4     $n;
$n = 4     4;
$n = 4   5;
9 = 4   5;

CodePudding user response:

The expression is generally interpreted as:

ADD(  $n,  $n)

which becomes ADD(4,5).

  •  Tags:  
  • php
  • Related