开发者

Subtracting 1 from a value and storing it in another variable

开发者 https://www.devze.com 2023-02-13 02:42 出处:网络
I vaguely remember running into this problem before, but I\'m wondering if this just doesn\'t work in PHP:

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

echo $counter; // ou开发者_开发技巧tputs 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


What you want is the pre-decrement operator:

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


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;
?>
0

精彩评论

暂无评论...
验证码 换一张
取 消