0

I'm follow an tutorial on sololearn website, and one of the section is operator. I came across this question that is very confusing to me.

Question:

What is the result for $b?

$a=2; 
$b= $a++;

I think it is three. Because $a = 2, and $b = 2+1. 2 + 1 = 3. But it says the answer is 2.

Any explainnation will be excepted.

  • 2
    it would be three if the operator was ++$a – Aleksandar Nov 26 '20 at 22:17
  • Can you explain why? –  Nov 26 '20 at 22:21
  • It's because `$var++` _post-increments_ the value and `++$var` _pre-increments_ the value. In other words the `++` following the variable assigns/uses the variable in it's current state and then increments it afterwards. Where as `++` before the variable increments the value and then uses/assigns it! – Steven Nov 26 '20 at 23:09
  • `$a++` increments the value of `$a` and returns *the old value*. `++$a` increments the value of `$a` and returns *the new value*. This is either confusing or counterintuitive to many. My suggestion is: **never** use `++` in any other way than a standalone expression. – MC Emperor Nov 26 '20 at 23:15
  • You can be explicit with the mathmaticians favourite (sarcasm): `$a = $a + 1;` then assign to $b. Or just do `$b = $a + 1;` if you don't want to increment $a. – Progrock Nov 27 '20 at 00:24

0 Answers0