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/>";
}
?>
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