What will the following snippet print, and why?
- $count = 0;
- print $count++;
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.
By all accounts, I think the answer should be
++ operator does the same as
+=1. I hope I'm not falling into a boolean trap here :D
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. :)
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.