Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the pre/post increment operator behave wrongly?

Tags:

php

Why the values of variable in PHP does not have a consistent behavior in following code?

<?php
$piece = 10;
// output is 10 10 10 10 11 12 
echo $piece . $piece . $piece . $piece++ . $piece . ++$piece;

$piece = 10; 
// output is 10 10 10 11 12 
echo $piece . $piece . $piece++ . $piece . ++$piece;

$piece = 10; 
// output is 11 10 11 12 
echo $piece . $piece++ . $piece . ++$piece;
?>

The question is why is the first output in the last example equal to 11? instead of 10 as it give in above 2 examples.

like image 390
Jall Oaan Avatar asked Jan 13 '15 23:01

Jall Oaan


People also ask

How does pre increment and Post increment work?

Pre-increment (++i) − Before assigning the value to the variable, the value is incremented by one. Post-increment (i++) − After assigning the value to the variable, the value is incremented.

How does pre increment operator work?

The pre increment operator is used to increment the value of some variable before using it in an expression. In the pre increment the value is incremented at first, then used inside the expression. if the expression is a = ++b; and b is holding 5 at first, then a will hold 6.

What is the difference between pre increment and post increment in JavaScript?

JavaScript Increment operator (++ )In the first case (i.e. post-increment) the operator increases the variable var1 by 1 but returns the value before incrementing. In the second case (i.e. pre-increment) the operator increases the variable var1 by 1 but returns the value after incrementing.

What is the difference between pre increment and post increment in C++?

The pre-increment operator increments the value of a variable at first, then sends the assign it to some other variable, but in the case of postincrement, it at first assign to a variable, then increase the value.


1 Answers

From http://php.net/manual/en/language.operators.precedence.php:

Operator precedence and associativity only determine how expressions are grouped, they do not specify an order of evaluation. PHP does not (in the general case) specify in which order an expression is evaluated and code that assumes a specific order of evaluation should be avoided, because the behavior can change between versions of PHP or depending on the surrounding code.

<?php
$a = 1;
echo $a + $a++; // may print either 2 or 3

$i = 1;
$array[$i] = $i++; // may set either index 1 or 2
?>

In other words, you cannot rely on the ++ taking effect at a particular time with respect to the rest of the expression.

like image 166
Oliver Charlesworth Avatar answered Oct 05 '22 06:10

Oliver Charlesworth