PHP Question: Increment By One

11th April 2011

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.

Comments

Permalink

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

Mihai Baboi (Mon, 04/11/2011 - 19:09)

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. :)

Mihai Baboi (Wed, 04/13/2011 - 06:29)

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.

Permalink
thank you so much as you are IT Proffsional

Anonymous (Mon, 04/14/2014 - 08:01)

Add new comment

The content of this field is kept private and will not be shown publicly.