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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With