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
The decrement operator is represented by two minus signs in a row. They would subtract 1 from the value of whatever was in the variable being decremented. The precedence of increment and decrement depends on if the operator is attached to the right of the operand (postfix) or to the left of the operand (prefix).
Adding 1 to a variable is called incrementing and subtracting 1 from a variable is called decrementing.
To increment a variable means to increase it by the same amount at each change. For example, your coder may increment a scoring variable by +2 each time a basketball goal is made. Decreasing a variable in this way is known as decrementing the variable value.
For example, incrementing 2 to 10 by the number 2 would be 2, 4, 6, 8, 10. 2. An increment is also a programming operator to increase the value of a numerical value. In Perl, a variable can be incremented by one by adding a ++ at the end of the variable.
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 $a
to a value 1
that's off in memory somewhere.
With the second line, you are doing $a = $a-- + 1
so you are creating a new value and setting that to $a
. The $a--
retrieves the value of the original $a
, which is 1
and adds 1
to make 2
and creates that value somewhere else in memory. So now you have a variable $a
which points to 2
and some other value 1
off in memory which along the way decremented to 0
, but nothing is pointing at it anymore, so who cares.
Then you echo $a
which points to your value of 2
.
Edit: Testing Page
$a-- decrements the value after the line executes. To get an answer of 1, you would change it to --$a
<?php
$a = 1;
$a = --$a +1; // Decrement line
echo $a;
?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With