Reputation: 1881
I have a PHP function which returns a number, and I want to display it as a percentage from 1 - 100. Anything over 100 should just be reevaluated to 100. How can I do that?
$myvar = 120;
$my_percentage = <$myvar, max value is 100>
I'm using Laravel, if that helps. Thanks!
Upvotes: 2
Views: 2216
Reputation: 74
This is the simplest way for restricting the number
$my_percentage = min(100, $myvar);
Upvotes: 6
Reputation: 57121
If you want to ensure the value is always less than or equal to 100, then take the minimum (using min()
) of the value and 100...
$my_percentage = min(100, $myvar);
Upvotes: 6
Reputation: 27119
The simplest would be to just use a ternary operator.
$myvar = 120;
$my_percentage = $myvar > 100 ? 100 : $myvar;
So that in case $myvar
is bigger than 100 it will just assign 100 to $my_percentage
.
Upvotes: 3
Reputation: 134
There is a few ways todo this, just quick without context this is my first thought.
$my_precentage = ($myvar < 100) ? $myvar : 100;
Upvotes: 2