0

Can someone help me understand this? When I output the code in PHP it gives the answers a is 11 and b is 10, but I thought if I were to echo a it would equal 10, where as if I echo b it would be 10+1 ($a++).

See code

$a = 10;
$b = $a++;
  echo $a;
  echo $b;
nicedood
  • 53
  • 1
  • 8

1 Answers1

0

Let me give you an idea using cases and interpretations:

Assuming:

let a = 10;
let b = 0;

Case 1: b = a++

Interprets to:

b = a;     // b now is 10
a = a + 1; // a now is 11

Case 2: b = a--

Interprets to:

b = a;     // b now is 10
a = a - 1; // a now is 9

Case 3: b = ++a

Interprets to:

a = a + 1; // a now is 11
b = a;     // b now is 11

Case 4: b = --a

Interprets to:

a = a - 1; // a now is 9
b = a;     // b now is 9

Note

Expression like a++ or --a changes the original variable. If you don't want to change the original variable, you need to write it like:

b = a + 1;
// Now b = 11 and a is still 10
yqlim
  • 5,648
  • 3
  • 15
  • 36