# Add "1" and overwrite the previous value [closed]

I have a cookie where a number is stored. When I want to add "1" to the stored number and then overwrite it, I use this php code:

$temp =$_COOKIE['mycookie']++;
$_COOKIE['mycookie']=$temp;


Is it the best way to do that?

• You have edited to say your code is working, yet, in its current form, it can't be. $temp will be the value of the cookie prior to the post-increment is applied, and you are then overwriting the cookie with the unchanged value. i.e. you save the cookie value to temp, the you increment it, then you restore the cookie value to what it was before the increment. That is what your code does, which is not what you are describing that you actually get. There is a discrepency. Jun 17, 2014 at 17:37 • You guys were right, the code is broken. Ignore the votes to open as his code does not do what he says it does. Looks like @rolfl beat me to it Jun 17, 2014 at 17:40 • That's weird, I was pretty sure it worked. Maybe I remembered of an other code I had written which was similar and worked. I really apologize, I should've not trusted of my memory and tested again the code before posting my question. – user46302 Jun 17, 2014 at 17:52 ## 3 Answers I think what you may be looking for is found on this page. This is happening because of the ++ being used as a post-increment instead of a pre-increment. Essentially what is happening is you're saying, "set$cookie to the value of $_COOKIE['count'], and then increment$_COOKIE['count'].

Go for ++$_COOKIE['mycookie']; instead and let us know how that works out. I'm certainly no expert in PHP, but in most languages I've used (and it seems PHP is no exception) there's a += operator which seems like it would be better for this situation: $_COOKIE['mycookie'] += 1


There's nothing wrong with just

\$_COOKIE['mycookie']++;