Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP PHP Basics Unit Converter Mathematical Manipulations

Teacher Russell
Teacher Russell
16,873 Points

What are they talking about?

It's not 6 as I would expect. Why isn't it 6? I just watched the video, followed every exercise, took notes.....What happens? ++ Doesn't add one? -- doesn't take one away?

2 Answers

Jennifer Nordell
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Teacher

Hi there! I think you may be referring to the question that displays this code.

$a = 5; 
var_dump($a++); 

Here's what's happening. First we set $a to 5. So far so good. Now the next part is we increment 5 by one. The thing is the increment comes after the $a which means that it will var_dump the value of a and then increment it by 1. After the value is echoed out, the value of $a is 6, but it's already been echoed.

We could reverse this though by doing:

$a = 5; 
var_dump(++$a);

This would set $a to 5. So far so good. Then it would increment $a by one (setting the value to 6) and then it would echo out. The value after the echo is still 6.

The big question here is does the value get incremented before or after the echo.

Hope this clarifies things! :sparkles:

andren
andren
28,558 Points

I'm assuming you are asking about the question with this code:

$a = 5; 
var_dump($a++); 

When ++ is used after a variable name it does two things in the following order:

  1. Return the current value of the variable, which is 5 in this case.
  2. Increase the value of the variable by 1.

Since var_dump prints out whatever value is returned it prints 5, even though $a gets set to 6 after that line has run. If you want the value to be increased before the value is returned then you should place the ++ before the variable name like this:

$a = 5; 
var_dump(++$a);