Difference $i++ and ++$i when 0 - php

I came along this script lately:
$i = 0;
$x = $i++; $y = ++$i;
print $x; print $y;
The output was 02. I can imagine that you can't count +1 on $i with ++ while it is 0, but why does $y output as 2? And why isn't the output 11 or 01?

post increment vs pre increment.
Post: Trailing $i++ means that $i is returned and then incremented after.
Pre: Preceding ++$i means that $i is incremented and that result is returned.
So $x is set to 0 (the initial value of $i) and then incremented. $i is now equal to 1. Then $i is incremented again to 2 and that value is set in $y. So in the end, $x=0 and $y=2 and $i=2. Your code could be rewritten as:
$i=0;
//x, post increment, set x to i then increment after.
$x=$i;
$i=$i+1;
//y, pre increment, increment first and then set y to i.
$i=$i+1;
$y=$i;
Same thing applies to the decrement operator --$i and $i--.

Related

Why post increment and pre increment is equal here?

When I try to use the below code as post-increment or pre-increment of $j the result is always the same. Do you know why? Please tell me. Thank you.
<?php
$j = 1;
while( $j < 20 ) {
$j++;
echo "1 * $j is equal to $j <br/>";
}
?>
In this code:
$j = 1;
while( $j < 20 ) {
$j++;
echo "1 * $j is equal to $j <br/>";
}
It doesn't matter whether you write $j++; here or ++$j; here because $j++ is on a line by itself. It's not part of another expression that would come before or after the increment of $j. When it's on a line by itself $j++; and ++$j; do the same thing. Ask your self: "increment $j before what?" or "increment $j after what"?
Now if instead you had:
$j = 1;
while( $j++ < 20 ) {
echo "1 * $j is equal to $j <br/>";
}
$j would be incremented after its value was compared with 20. This loop will show values of $j in the output from 2 through 19.
Whereas if you wrote
$j = 1;
while( ++$j < 20 ) {
echo "1 * $j is equal to $j <br/>";
}
The value of $j would be incremented before $j was compared with 20. This loop will show values of $j in the output from 2 through 20.
That's because now $j is part of a bigger expression where the order of increment matters.
In this code $j=1 we initialize then we check the condition it satisfy the condition then it increment the value of $j=2 now this original value of $j is 2. Hence in echo statement 1*$j is equal to $j means 1*2 is equal to 2.
Like this all iteration will be follow untill the loop ends.
As if the pre increment we use same case will happen first value increment then by original value calculate the same output

Explain Alternative PHP For Loop Syntax: for ($i = 1, $j = 0; $i <= 10; $j += $i, print $i, $i++);

This example has been given as an alternative example (example 4 to be precise) for writing for loops on PHP.net.
for ($i = 1, $j = 0; $i <= 10; $j += $i, print $i, $i++);
I understand for loops, I just don’t understand why the variable, $j, is declared in this version of writing a for loop that prints the numbers 1 to 10.
FYI: Removing the variable from the for loop makes absolutely no difference to the result.
I think that it's just here for illustrate the fact that you can use multiple statement with commas.
It's useless here but show an example of the syntax for :
[...] Each of the expressions can be empty or contain multiple expressions separated by commas. In expr2, all expressions separated by a comma are evaluated but the result is taken from the last part. [...]
While it doesn't seem to be necessary in this example. It appears that $j is storing the summation of the iterations:
1+2+3+4+5+6+7+8+9+10 = 55
Which can be useful in some situations. So that would mean this style of looping is for the equivalent of doing several operations on each iteration, such as getting the summation, average, largest value, etc. The point of the example is that you can apply several statements separated by commas.
Explanation
for ($i = 1, $j = 0; $i <= 10; $j += $i, print $i, $i++);
for loops takes three part separated by semicolon (;).
Initialize
Compare and test
Increment or Decrements.
Here $i=1, $j=0 is initialization.
$i<=10; is compare and test
$j += $i, print $i, $i++ is increment or decrements part
Now in your increment or decrements part you have three task.
1. is increment $j with last $i
2. print $i
3. increment $i by 1
So in your program $j is not useful. Because it is not taking part of
either print or compare and test.
So the loop is just very simple if you remove $j from every where and write it as
for ($i = 1; $i <= 10; $i++){
print $i;
}
But that $j variable could be used after the loop where from you have taken this code block.
LIKE
for ($i = 1, $j = 0; $i <= 10; $j += $i, print $i, $i++);
print $j;
We can remove $j and have the same result:
for ($i = 1; $i <= 10; print $i, $i++);

Incrementing numbers doesn't give an error

How come this code below echo's 2 and does not give an error, does it just ignore +1+2+3+4 ?
I've searched but couldn't find an answer.
<?php
$i = 1;
$i+++1+2+3+4;
echo $i;
That line:
$i+++1+2+3+4;
Says:
Increment $i
Add the value of $i pre increment to +1+2+3+4, but don't store the result anywhere.
Hence $i == 2.
If you wouldn't want it to be ignored, you should store the result:
$i = $i+++1+2+3+4;
You never assign the completed operation anywhere:
These two are functionally equivalent:
$i++;
$i = $i + 1;
both will increment $i by 1, and save that incremented value in $i
With $i+++1+2+3+4 you're essentially executing
($i++) + 1 + 2 + 3 + 4
which is
$i = $i + 1;
1 + 2 + 3 + 4; // useless, result not stored anywhere
so which increments $i by 1, saves that to $i, then does the other additions. But since those aren't being saved anywhere, the result is thrown away.
if you had
php > $i = 1;
php > $i = $i+++1+2+3+4;
^^^^^----add this
php > echo $i;
11
then it would have worked as you expect.
All is fine. You just forgot the assignment, so i is affected only by ++ operator:
<?php
$i = 1;
$x = $i+++1+2+3+4;
echo "{$i} vs "{$x}";
would return
2 vs 11
$i++ means add 1 to $i.
and like python, the +1+2+3+4 means add the value of $i pre increment to +1+2+3+4 but don't store it anywhere.(so no memory address or anything like that...).
so what you get is just $i==2

Pre-incrementation vs. post-incrementation

How are they different? Here's what I'm thinking, but I'm not sure....
If you use pre-incrementation, for example in a for loop with ++j, then you are basically saying: "Make a copy of the value of j for use in the loop, then increment j, then go through the statements in the loop with the copy of j." If you are using post-incrementation in the same loop j++, then you are basically saying: "Make a copy of the value of j for use in the loop, then go through the statements in the loop with the copy of j, then increment j."
The reason I'm unsure is because I've created a for loop that multiplies the value of j by 10 and then outputs the result for j=1 through j=12, using both post- and pre-incrementation. The human readable output is exactly the same with post- and pre-incrementation. I'm thinking, 'How are the outputs exactly the same if there isn't some kind of copy operation involved?'
So, I'm guessing the difference between pre- and post-incrementation truly becomes important, in php, when I use references (which act as pointers in php) rather than names for return values? This would be because copies of references aren't made, so pre-incrementation would be: "Increment j, then go through the statements in the loop with the changed value of j, then increment j again...," whereas post-incremetation would look like: "Use the value of j for the statements in the loop, then change the value of j, then go through the loop with the new value of j..."
Pre- or post-incrementing do not magically delay things until later. It's simply inline shorthand.
// pre-increment
$var = 5;
print(++$var); // increments first, then passes value (now 6) to print()
// post-increment
$var = 5;
print($var++); // passes value (still 5) to print(), then increments
Now let's look at a loop.
for ($i = 0; $i < 9; $i++) {
print($i);
}
The last part of the loop declaration (the $i++) is simply the statement to execute after each time through the loop. It "passes" the value to nowhere, then increments it. $i isn't used anywhere at that time. Later when the next statement is executed (print($i);), the value of $i has already increased.
// add 1, then do nothing with $i
for ($i = 0; $i < 9; ++$i) {}
// do nothing with $i, then add 1
for ($i = 0; $i < 9; $i++) {}
Whichever way you do it, $i will be the same within the loop.
If it helps, you can think of them as small routines that kind of do this:
// ++$i
{
$i = $i + 1;
return $i;
}
// $i++
{
return $i;
$i = $i + 1;
}
As I reread your question, I think the confusion is more with how the loop works than how increment operators work. Keeping in mind that the increment is a straightforward, all-at-once operation, here's how third expression in the loop works.
// here's a basic loop
for ($i = 0; $i < 9; $i++) {
// do loop stuff
print($i);
}
// this is exactly what happens
for ($i = 0; $i < 9; ) {
// do loop stuff
print($i);
$i++;
}
Just because that last line can be put in the loop declaration doesn't give it any special powers. There are no references or anything used behind the scenes. The same $i variable is seen both inside and outside the loop. Every statement inside or outside the loop directly looks up the value of $i when necessary. That's it. No funny business.
When doing $x++, you are post-incrementing... This means that the incrementation will only occur after the statement has been evaluated.
So, given the following code:
$x = 10; $y = 0; $z = 5;
$y = $z * $x++;
PHP does this:
$x = 10; $y = 0; $z = 5;
$y = $z * $x++;
// Ignore Post-Increment, Evalutate
$y = $z * $x;
$y = 5 * 10;
// Now Increment x - POST-INCREMENT
$x = $x + 1;
$x = 10 + 1;
$x = 11;
// Continue evaluating statement
$y = 5 * 10;
$y = 50;
When doing ++$x, you are pre-incrementing... This means that the incrementation will occur before the statement is evaluated:
$x = 10; $y = 0; $z = 5;
$y = $z * ++$x;
// Do Pre-Increment
$x = $x + 1;
$x = 10 + 1;
$x = 11;
// Evaluate
$y = $z * $x;
$y = 5 * 11;
$y = 55;
In the case of a for loop in PHP, PHP evaluates a for loop as follows:
for($i = 0; $i < 30; $i++) {
doSomething();
}
// Is evaluated EXACTLY as such by PHP
$i = 0;
while($i < 30) {
doSomething();
$i++;
}
The first expression ($i = 0) is evaluated (executed) once unconditionally at the beginning of the loop.
In the beginning of each iteration, $i < 30 is evaluated. If it evaluates to TRUE, the loop continues and the nested statement(s) are executed. If it evaluates to FALSE, the execution of the loop ends.
At the end of each iteration, $i++ is evaluated (executed) as an independent expression.
Therefore, post-incrementing or pre-incrementing a variable as the third expression in the loop doesn't have an effect on the behavior of it. In this simple case, both expressions will behave exactly the same.
However, in a complex loop such as the following:
for($i = $j = 0; $i < 30; $i += ++$j) {
$j = getResult($j);
}
Post-incrementing or pre-incrementing $j directly affects the value of $i according to the examples above. In this case, you need to choose exactly what you want to do.
$i = 0;
echo $i++;
echo $i;
$j=0;
echo ++$j;
echo $j;
Pre increment display incremented value. But Post increment display value then increment. About code will output 01 and 11

What's the difference between ++$i and $i++ in PHP?

What's the difference between ++$i and $i++ in PHP?
++$i is pre-increment whilst $i++ post-increment.
pre-increment: increment variable i first and then de-reference.
post-increment: de-reference and then increment i
"Take advantage of the fact that PHP
allows you to post-increment ($i++)
and pre-increment (++$i). The meaning
is the same as long as you are not
writing anything like $j = $i++,
however pre-incrementing is almost 10%
faster, which means that you should
switch from post- to pre-incrementing
when you have the opportunity,
especially in tight loops and
especially if you're pedantic about
micro-optimisations!"
- TuxRadar
For further clarification, post-incrementation in PHP has been documented as storing a temporary variable which attributes to this 10% overhead vs. pre-incrementation.
++$i increments $i, but evaluates to the value of $i+1
$i++ increments $i, but evaluates to the old value of $i.
Here's an example:
$i = 10;
$a = $i++;
// Now $a is 10, and $i is 11
$i = 10;
$a = ++$i;
// Now $a is 11, and $i is 11
There is sometimes a slight preformance cost for using $i++. See, when you do something like
$a = $i++;
You're really doing this:
$temporary_variable = $i;
$i=$i+1;
$a=$temporary_variable;
++$i is pre-incrementation
$i is incremented
the new value is returned
$i++ is post-incrementation
the value of $i copied to an internal temporary variable
$i is incremented
the internal copy of the old value of $i is returned
++$i //first increment $i then run line
$i++ //first run line then increment $i
this example elplains simply
<?php
$x = 10;
echo $x++. ' '.$x; // the result is 10 and 11
echo '<br>';
$y = 10;
echo ++$y. ' ' .$y; // the result is 11 and 11
// so the $x++ is not showing +1 at first but the next time
// and the ++y is showing +1 first time but not increasing next
in this case there is no difference:
for($i = 0;$i<3;++$i)var_dump $i;
/*
int(0)
int(1)
int(2)
*/
for($i = 0;$i<3;$i++)var_dump $i;
/*
int(0)
int(1)
int(2)
*/
but:
for($i = 0;$i<3; $j = ++$i )var_dump($j);
/*
NULL
int(1)
int(2)
*/
for($i = 0;$i<3; $j = $i++ )var_dump($j);
/*
NULL
int(0)
int(1)
*/
Difference is: ++$i will increment $i variable and return updated value, while $i++ will return original value, so increment it.
$prefix = 1;
$postfix = 1;
echo ++$prefix; // 2
echo $postfix++; // 1
To explain jldupont's point:
$i = 1;
$x = $i++;
echo $x; // prints 1
$x = ++$i;
echo $x; // prints 3
Another way of looking at pre and post incrementing is that it's shorthand for combining 2 statements.
Pre-incrementing
// long form
$y = $y + 1;
$x = $y; // any statement using $y
// shorthand
$x = ++$y; // the same statement using $y
Post-incrementing
// long form
$x = $y; // any statement using $y
$y = $y + 1;
// shorthand
$x = $y++; // the same statement using $y
$i++ is known as post-increment. It increments the value of $i only after assigning the original value of $i to $j first.
++$i is known as pre-increment. It increments the value of $i before assigning the value to $j, so the updated value of $i will be assigned to $j.
Hence,
$i = 4;
$j = $i++;
// Now, $i = 5 and $j = 4
$i = 4;
$j = ++$i;
// Now, $i = 5 and $j = 5
These theories apply in a similar manner for decrementing as well.
Hope this helps!
It's probably best-illustrated by an example...
Post-increment:
$zero = 0;
$n = $zero++; //$n is zero
Pre-increment:
$zero = 0;
$n = ++$zero; //$n is one
Short answer:
Prefix increases the value and returns the value increased
Postfix increases the value and returns the value before it was increased
Prefix is faster
Long answer: If you think a little about it, how you would implement those yourself, you will probably realize why prefix is faster. Truth to be told, postfix is actually (often) implemented using prefix:
const T T::operator ++ (int) // postfix
{
T orig(*this);
++(*this); // call prefix operator
return (orig);
}
Avoid postfix unless you have a specific reason not to. The difference in speed can be quite a lot for complex datatypes.
I actually looked this up a few days ago. Heres my source.
The main purpose of the post-fix increment operator is usage like this:
while(*condition*)
$array[$i++] = $something;
This is a very elegant way, how to get around some array iterations.
Breakdown:
Variable $something will be assigned to the array element indexed with $i
Variable $i will be incremented
Iteration is at the end, condition will be checked
In all other cases, you should use the prefix operator. It makes the code much more clear (You can be sure, that you already work with the incremented value of particular variable).
I ran the following code to test if ++$i is 10% faster than $i++. I admit, the code does not have a stable outcome but even then I should at least have seen some numbers near the 10%. The highest I got was 4-4.5% approximately.
<?php
$randomFloat = rand(0, 10) / 10;
$before1 = microtime(true);
for($i=0; $i <1000000; ++$i){
$rand = (rand(0, 10) / 10) * (rand(0, 10) / 10);
}
$after1 = microtime(true);
echo 'it took '.($after1-$before1) . ' seconds fot ++$i<br />';
$before2 = microtime(true);
for($i=0; $i <1000000; $i++){
$rand = (rand(0, 10) / 10) * (rand(0, 10) / 10);
}
$after2 = microtime(true);
echo 'it took '.($after2-$before2) . ' seconds fot $i++<br /><br />';
echo '++$i is '.((($after1-$before1)*100)/($after2-$before2)-100).'% faster than $i++';
Both operators still do what their syntax implies: to increment. Regardless of prefix or postfix, the variable is sure to be incremented by 1. The difference between the two lies in their return values.
1. The prefix increment returns the value of a variable after it has been incremented.
2. On the other hand, the more commonly used postfix increment returns the value of a variable before it has been incremented.
// Prefix increment
let prefix = 1;
console.log(++prefix); // 2
console.log(prefix); // 2
// Postfix increment
let postfix = 1;
console.log(postfix++); // 1
console.log(postfix); // 2
To remember this rule, I think about the syntax of the two. When one types in the prefix increment, one says ++x. The position of the ++ is important here. Saying ++x means to increment (++) first then return the value of x, thus we have ++x. The postfix increment works conversely. Saying x++ means to return the value of x first then increment (++) it after, thus x++.

Categories