2

I vaguely remember running into this problem before, but I'm wondering if this just doesn't work in PHP:

echo $counter; // outputs 4
$output = $counter--;
echo $output; // outputs 4

If I do something like:

$output = $counter - 1;

I have no problems whatsoever.

Can someone shed some light on this?

Thanks, Ryan

NightHawk
  • 3,633
  • 8
  • 37
  • 56

2 Answers2

11

What you want is the pre-decrement operator:

echo $counter; // outputs 4
$output = --$counter;
echo $output; // outputs 3
AndreKR
  • 32,613
  • 18
  • 106
  • 168
8

Your code, using post-decrement, should be read as:

  • set the value of $counter to $output; then
  • decrement $counter

What you want is the following (pre-decrement), which says

  • decrement $counter; then
  • set the value of $counter to $output

The code is:

<?php
  $counter = 4;
  echo $counter;
  $output = --$counter;
  echo $output;
?>
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
Michelle Tilley
  • 157,729
  • 40
  • 374
  • 311
  • Crap :) That absolutely makes sense... and actually, I read about that before, but since I never had to use it, forgot it again. Since #4 gets assigned before it is decremented, whatever happens to #3? It decrements to #3 and then just gets lost in cyberspace? – NightHawk Feb 24 '11 at 23:47
  • In the original code, `$output` would have been 4, and `$counter` would have been 3. You just assigned the value to `$output` *before* $counter got decremented. – Michelle Tilley Feb 25 '11 at 00:42
  • the 3 stays in `$counter` variable – Elwhis Feb 25 '11 at 00:44