Using $var++ and ++$var and the differences

Here is a couple examples of how they work.

Basically if -- or ++ is before a variable and it's in a conditional test, you will be testing for whatever the variables value is plus one.

If -- or ++ is after the variable and it's in a conditional test, you will be testing for whatever the variables value is at that time. The variable will be incremented by one, but in the test it will be what it's value was before the increment.

<?php
$x = 9;
if(++$x == 10)
{
     echo("++x goes ahead and adds 1 to x so it does equal 10");
}
?>
<?php
$x = 9;
if($x++ == 10)
{
     echo("x++ waits to actually add 1 to x so it doesn't equal 10
               and this message will never be echoed"
);
}
?>

Using $x++ and ++$x is most useful if you want to increment a variable while testing it in a conditional statement before or after the condition is tested.

Page Comments (Click to edit)






[Click to add or edit comments])

Please prepend comments below including a date

Design by N.Design Studio, adapted by solidGone.org (version 1.0.0)
Have a nice day.