Friday, 10 August 2018

PHP Question: Increment By One

Question

What will the following snippet print, and why?
  1. $count = 0;
  2. 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:
  1. $count = 0;
  2. 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.

0 comments:

Post a Comment