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



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

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

使用三元运算符:

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

?之前的子句被计算为布尔值。如果是true,则将冒号之前的子句分配给变量;如果是false,则冒号后面的子句。

另请参阅http://php.net/manual/en/language.operators.comparison.php

假设零是可接受的

在这个问题中,我们被告知,如果数字大于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,则返回:后面的任何值。在上面的解决方案中,我嵌套了这个运算符,如果条件为false,则返回到另一个三元运算。

假设零是不需要的

我在这里假设0是一个可以接受的数字。如果不是,并且一个数字必须是最小的1,或者更大的正数,你可以做一个更简单的版本:

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

因此,如果$commentPoints小于或等于0,则$commentPointsOff接收值1。否则,它将接收较大的正值。

如果零在不可接受的数字范围内,只需使用以下命令:

$commentPointsOff = max(1, $commentPoints);

如果零是可接受的,则使用此

$commentPointsOff = max(0, $commentPoints);

最新更新