I found a piece of code (from one of our developer) and I was wondering why the output of this is 2?
<?php
$a = 1;
$a = $a-- +1;
echo $a;
thanks
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
I’ll give my explanation a whirl. We’re talking about a variable referencing some value off in the system.
So when you define
$a = 1, you are pointing the variable$ato a value1that’s off in memory somewhere.With the second line, you are doing
$a = $a-- + 1so you are creating a new value and setting that to$a. The$a--retrieves the value of the original$a, which is1and adds1to make2and creates that value somewhere else in memory. So now you have a variable$awhich points to2and some other value1off in memory which along the way decremented to0, but nothing is pointing at it anymore, so who cares.Then you echo
$awhich points to your value of2.Edit: Testing Page