0

Please provide me the proper solution of this script with explanation:

 $a = 5;
 $c = $a-- + $a-- + --$a - --$a;
 echo $c;

What will be the value of $c = 10; Why?

Teun Zengerink
  • 4,277
  • 5
  • 30
  • 32
PPS
  • 542
  • 1
  • 8
  • 25

4 Answers4

4

From reading the script above and the following to assertions

$var++, $var--  //Use value then apply incremnet, decrement
++$var, --$var  // Increment, decrement then use vakue

you can rewrite the expression for ease of understanding.

$a = 5;
$c = $a--;   // $c = 5, $a = 4
$c += $a--;  //$c = 9, $a = 3
$c += --$a   // $c = 11, $a = 2 ($a drops to two before use)
$c -= --$a   //$c = 10  $a = 1 ($a drops to one before use);
CBusBus
  • 2,321
  • 1
  • 18
  • 26
2

++ and -- produce the same end result - incrementing or decrementing the variable - whether applied before of after the variable name, the difference comes when it is used as part of a larger statement.

Consider this:

$a = 5;
$a--;
echo $a; // 4

$a = 5;
--$a;
echo $a; // 4

So you see, they produce the same end result - $a get decremented by one. I'm sure this is what you were expecting.

However:

$a = 5;
echo $a--; // 5
echo $a; // 4

$a = 5;
echo --$a; // 4
echo $a; // 4

In this example, $a is still decremented after the operation, but the order in which the decrement happens and the value is used is different. For $a-- the value is used before the decrement, and for --$a the value is used after.

So for your example code:

$a = 5;    //  Operations in order of occurence:
$c = $a--  //  $c = 5;          $a = 5 - 1  == 4;
   + $a--  //  $c = 5 + 4 == 9; $a = 4 - 1  == 3;
   + --$a  //  $a = 3 - 1 == 2; $c = 9 + 2  == 11;
   - --$a; //  $a = 2 - 1 == 1; $c = 11 - 1 == 10; 
echo $c;   //  10
DaveRandom
  • 87,921
  • 11
  • 154
  • 174
1
$a = 5 ; // $a = 5
$c = $a-- // $c = 5 $a = 4
+
$a-- // $c = 9 $a = 3
+
--$a // $c = 11 $a = 2
-
--$a // $c = 10 $a = 1
;
echo $c ; // $c = 10
vimdude
  • 4,447
  • 1
  • 25
  • 23
1

The expression $a-- is post-decrement, which means it first returns $a and then decrements $a by one. The expression --$a is pre-decrement which first decrements $a by one and then returns $a.

Taking the above into account, this means $c = 5 + 4 + 2 - 1 = 10.

Smi
  • 13,850
  • 9
  • 56
  • 64