PHP变量值取决于另一个变量的值

时间:2011-06-28 03:08:34

标签: php

如果$commentpointsoff大于1,如何使变量$commentpoints等于$commentpoints,如果$commentpoints小于零,如何变为1?

4 个答案:

答案 0 :(得分:2)

$commentpoints = ...;
$commentpointsoff = ...;
if ($commentpoints > 1) {
    $commentpointsoff = $commentpoints;
} else if ($commentpoints < 0) {
    $commentpointsoff = 1
}

答案 1 :(得分:1)

假设零是可接受的

在问题中,我们被告知如果数字大于1则使用数字,如果数字小于零则使用数字。如果数字为零,我们不知道该怎么办。在第一个答案中,我假设零是可接受的数字。

传统的if-else语句会很好用,但我想我会提供一个使用三元运算符的例子。它可能看起来有些令人生畏,但是当你理解语法时它会变得非常有吸引力:

$commentPoints = -12;

$commentPointsOff = ( $commentPoints > 1 ) 
  ? $commentPoints 
  : ( ( $commentPoints < 0 ) ? 1 : 0 );

echo $commentPointsOff; // 1, because -12 is less than zero

一个积极的例子:

$commentPoints = 5;
$commentPointsOff = ( $commentPoints > 1 ) 
   ? $commentPoints 
   : ( ( $commentPoints < 0 ) ? 1 : 0 ) ;

echo $commentPointsOff; // 5, because 5 is greater than 1

如果这是您第一次使用三元运算符,请让我提供速成课程。它本质上是一个简化的if-else语句:

$var = (condition) ? true : false ;

如果我们的条件评估为true,则返回?之后的任何内容。如果条件评估为false,我们将返回:后的任何内容。在上面的解决方案中,我正在嵌套此运算符,如果条件为假,则返回另一个三元运算。

假设零是不需要的

我在这里假设0是可接受的数字。如果不是,并且数字必须至少为1,或者正数较大,则可以使用更简单的版本:

$commentPointsOff = ( $commentPoints <= 0 ) ? 1 : $commentPoints ;

因此,如果$commentPoints小于或等于0,则$commentPointsOff会收到1的值。否则,它会获得更大的正值。

答案 2 :(得分:1)

使用三元运算符:

$commentpointsoff = $commentpoints > 1 ? $commentpoints : 1;

?之前的子句被评估为布尔值。如果true,冒号前的子句被赋值给变量; if false,冒号后的子句。

另见http://php.net/manual/en/language.operators.comparison.php

答案 3 :(得分:1)

如果零在不可接受的数字范围内,请使用:

$commentPointsOff = max(1, $commentPoints);

如果零可以接受,请使用此

$commentPointsOff = max(0, $commentPoints);
相关问题