【问题标题】:Subtracting 1 from a value and storing it in another variable从一个值中减去 1 并将其存储在另一个变量中
【发布时间】:2011-07-03 23:06:49
【问题描述】:

我依稀记得以前遇到过这个问题,但我想知道这是否在 PHP 中不起作用:

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

如果我这样做:

$output = $counter - 1;

我没有任何问题。

有人能解释一下吗?

谢谢, 瑞恩

【问题讨论】:

  • $counter---- 直到表达式执行后才会出现。它被称为 POST 减量。

标签: php shorthand decrement


【解决方案1】:

你想要的是pre-decrement operator:

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

【讨论】:

    【解决方案2】:

    您的代码,使用后减量,应该读作:

    • 将$counter的值设置为$output;那么
    • 递减 $counter

    你想要的是以下(预减量),它说

    • 递减 $counter;那么
    • 将 $counter 的值设置为 $output

    代码是:

    <?php
      $counter = 4;
      echo $counter;
      $output = --$counter;
      echo $output;
    ?>
    

    【讨论】:

    • 废话 :) 这绝对是有道理的......实际上,我以前读过它,但由于我从未使用过它,所以又忘记了它。由于#4 在递减之前被分配,所以#3 会发生什么?它递减到#3,然后就迷失在网络空间中?
    • 在原始代码中,$output 应该是 4,$counter 应该是 3。你刚刚将值赋给了 $output 之前 $counter got递减。
    • 这3个留在$counter变量中
    猜你喜欢
    • 1970-01-01
    • 2015-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-31
    • 2019-11-07
    • 2021-04-11
    相关资源
    最近更新 更多