Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why 1 + decrementing the value + 1 = 2?

Tags:

operators

php

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

like image 218
Pat R Ellery Avatar asked Oct 16 '11 23:10

Pat R Ellery


People also ask

How do you decrement?

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).

How do you decrement a variable?

Adding 1 to a variable is called incrementing and subtracting 1 from a variable is called decrementing.

What does incrementing a variable mean?

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.

How do you increment a 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.


2 Answers

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

like image 107
animuson Avatar answered Oct 13 '22 22:10

animuson


$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;
?>
like image 34
James Williams Avatar answered Oct 13 '22 22:10

James Williams