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 trialLearning coding
Front End Web Development Techdegree Student 9,937 Points$a = 5; var_dump($a++); After running the console is 5?
Can someone explain the result above? Thanks.
5 Answers
Benjamin Verspeak
10,940 PointsFrom what I understand, When you run ($a++) it returns $a first and if you were to then var_dump($a) afterwards, it would now be 6.
So: <?php $a = 5; var_dump($a++); var_dump($a); ?>
will return: int(5) int(6)
Raphaël Seguin
Full Stack JavaScript Techdegree Graduate 29,228 PointsLet's look at sequentially (the way the computer sees it) :
- first :
$a = 5;
You assign the value 5 to the variable $a. - then : var_dump($a++); the var_dump() function displays the values of the arguments you pass it to. In our case, the argument is $a++. The expression $a++ does two things, in this order (the order is important) :
- it returns the variable $a
- then it increments the value of $a by one. So, since $a = 5, $a++ returns 5 and then var_dump($a++) returns 5. After that, the value of $a is incremented. You could easily check that if you wrote : var_dump($a++); var_dump($a); You'd see it doesn't show the same value the second time, because $a has been incremented after the first var_dump function was called but before the second one was called.
Does it help you to understand what's happening ?
cheers,
Raphaël
Raphaël Seguin
Full Stack JavaScript Techdegree Graduate 29,228 PointsHi, a++ returns the value of a, and then adds one to the value of a. ++a adds one to the value of a, and then returns the value of a.
cheers,
raphaël
Learning coding
Front End Web Development Techdegree Student 9,937 PointsThe answer is 5, not 6! And I don't understand why?
Micah Doulos
17,663 Points$a = 5; var_dump($a++);
=
$a = 5; Display the value of $a and afterwards add 1 (new value not displayed).
Damian Toczek
4,471 Pointswith var_dump($a++) you first dump the $a variable and after showing that variable it adds 1 to $a. with var_dump(++$a) it will first add 1 to $a and show it.