Skip to content
Advertisement

Incrementing/Decrementing $a++ and ++$a. Can someone help me explain this?

I have one variable:

$a = 5;

Let’s do the math below:

$a++ + $a- + -$a + ++$a + $a++ + ++$a - $a- + $a

With the help of the PHP language, I calculated the result as 22. But I don’t know why it got this result? Hope for a help!

Advertisement

Answer

Points to consider

  • $a++ : First $a value will be used in expression and then incremented.
$a = 5;
echo $a++;  // Will print 5 only, as $a is used first and then incremented.
echo $a;    // will print 6 as it is incremented in previous expression.

  • ++$a : First value is incremented and then incremented value of $a will be used in expressions.
$a = 5;
echo ++$a;  // Will print 6 as value is incremented first and then used in expression.

  • -$a : simple negation of any value
$a = 5; $b = -6;

echo -$a;  // -5
echo -$b;  // 6

  • Last but not least, $a-, it is -(minus) operator after $a, you can add space after it. But things turn out when another operator plus or minus is used b/w operands i.e. $a- + $b, you can say it does the operator multiplication.
-(minus) -(minus) ==> +(plus)
-(minus) +(plus)  ==> -(minus)
+(plus) -(minus)  ==> -(minus)
+(plus) +(plus)   ==> +(plus)

e.g.
$a = 5 ; $b = 10;

echo $a - - $b;  // $a + $b = 15
echo $a - + $b;  // $a - $b = -5
echo $a + - $b;  // $a - $b = -5
echo $a + + $b;  // $a + $b = 15

Now coming to your question

$a++ + $a- + -$a + ++$a + $a++ + ++$a - $a- + $a; 
==> simplify it with operator multiplication

($a++)   + $a - (-$a) + (++$a)   + ($a++)    + (++$a)   - $a - $a;
 5       + 6  - (-6)  + (7)      +  7        +  9       - 9  - 9;  // 22
(post +1)               (pre +1)   (post +1)   (pre +1)

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement