PHP Question: Increment By One

Question

What will the following snippet print, and why?

$count = 0;
print $count++;










Answer

The answer here is '0', the ++ causes the $count variable to have 1 added to it and is essentially the same as $count = $count + 1. However, the variable is returned before it is incremented.

In PHP it is possible to do both $count++ and ++$count to increment variables. With $count++ the variable returned and then incremented. Conversely, ++$count will increment the variable and then return it. This generally doesn't matter with regards to counting loops, but if we took the above example and changed it slightly to this:

$count = 0;
print ++$count;

The output would now be '1' because the variable gets incremented and then returned before it is printed. The difference is quite subtle but can clearly have definate consequences if you are not careful.

It is also possible to decrement (take 1 away) from a variable by using --$count or $count--, which work in the same way as the increment operators.

Comments

By all accounts, I think the answer should be 1. The ++ operator does the same as +=1. I hope I'm not falling into a boolean trap here :D

Permalink

You got me here. I've been using $count++ for years, and I never realised that there was a ++$count and about the implications of it. This has been very educating. Thanks. :)

Permalink

Yeah, this one is a little tricky, but is good to know about as you can print/use and increment a value in one line.

Name
Philip Norton
Permalink
thank you so much as you are IT Proffsional
Permalink

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
2 + 7 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.