TalkPHP

TalkPHP (http://www.talkphp.com/forums.php)
-   Absolute Beginners (http://www.talkphp.com/absolute-beginners/)
-   -   Increment, decrement.... (http://www.talkphp.com/absolute-beginners/4142-increment-decrement.html)

allworknoplay 04-15-2009 08:06 PM

Increment, decrement....
 
Hey guys,

Got a newbie and embarrassing question....

I thought that the ++ would add 1 to a number? Like so:

Code:

$test = 1;

$test2 = $test++;

echo "OUTPUT: $test2";

The output is still 1. I thought that the output should be 2?

Is the only way to use the ++ is in loops?

I thought that the ++ was a quick way to add "1" without having to do this:

$test2 = ($test + 1);

xenon 04-15-2009 09:02 PM

You meant this:

Code:

$a = 1;

$b = ++$a;

echo $b; // 2

//----------------//
// ...or...
//----------------//
$a = 1;

$a++;

$b = $a;

echo $b; // 2

$var++ first returns the value of the variable, and then increments it, whereas ++$var first increments the variable, and then returns its value.

Salathe 04-15-2009 09:06 PM

For that use, you would need to use a pre-increment rather than post-increment operator. With your original code, using a post-increment, the expression $test++ evaluates to 1 (this is used for the assignment) then the value is incremented. With a pre-increment, the expression ++$test evaluates to 2 which is used in the assignment to $test2

Full details: http://php.net/operators.increment

P.S. xenon beat me to it, both posts say the same thing.

allworknoplay 04-15-2009 10:10 PM

darn!!! Yes you guys are right!!

I forgot about doing ++$test...

You know sometimes you are so used to doing: $i++ in your loops you forget
you can do it the other way too!!

Thanks guys!!

Wildhoney 04-16-2009 11:12 AM

Hehe. I know what you mean!


All times are GMT. The time now is 10:48 AM.

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.1.0