开发者

PHP variable value dependent on the value of another variable

开发者 https://www.devze.com 2023-03-16 00:18 出处:网络
How do I make a variable $commentpointsoff which equals either $commentpoints if $commentpointsis greater than 1, or 1 if $commentp开发者_StackOverflow社区ointsis less than zero?$commentpoints = ...;

How do I make a variable $commentpointsoff which equals either $commentpoints if $commentpointsis greater than 1, or 1 if $commentp开发者_StackOverflow社区ointsis less than zero?


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


Use a ternary operator:

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

The clause before the ? is evaluated as a boolean. If true, the clause before the colon is assigned to the variable; if false, the clause after the colon.

See also http://php.net/manual/en/language.operators.comparison.php


Assuming Zero is Acceptable

In the question we are told to use the number if it's greater than one, and use one if the number is less than zero. We're not told what to do if the number is zero. In this first answer, I will assume zero is an acceptable number.

A traditional if-else statement would work well, but I thought I would provide an example using the ternary operator. It may look somewhat intimidating, but it can become very attractive when you understand the syntax:

$commentPoints = -12;

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

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

And a positive example:

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

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

If this is your first time using the ternary operator, let me give a crash course. It's essentially a simplified if-else statement:

$var = (condition) ? true : false ;

If our condition evaluates to true, we return whatever follows the ?. If the condition evaluates to false, we return whatever follows the :. In my solution above, I'm nesting this operator, and falling back on another ternary operation if the condition is false.

Assuming Zero is Unwanted

I'm assuming here that 0 is an acceptable number. If it's not, and a number must be a minimum of 1, or the larger positive number, you could do a simpler version:

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

So if $commentPoints is less-than or equa-to 0, $commentPointsOff receives a value of 1. Else, it receives the larger positive value.


If zero is within the range of unacceptable numbers, just use this:

$commentPointsOff = max(1, $commentPoints);

If zero is acceptable, use this

$commentPointsOff = max(0, $commentPoints);
0

精彩评论

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