How do I make a variable $commentpointsoff which equals either $commentpoints if $commentpointsis greater than 1, or 1 if $commentpointsis less than zero?
-
If the value is zero, do you leave it zero? Or, is the value always going to be 1, or greater than 1?Sampson– Sampson2011-06-28 03:40:39 +00:00Commented Jun 28, 2011 at 3:40
4 Answers
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
Comments
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.