Reputation: 47
I need a short if/else in PHP to compare two strings in percent:
if ($sum['cur'] 70% of $sum['max']) {
print ("Attention");
} else {
print ("OK");
};
$sum['cur']
and $sum['max']
are numbers. For example, if $sum['max']=100
and $sum['cur']=80
, I'd like to print a warning that 80% are in use.
Upvotes: 1
Views: 244
Reputation: 41810
Assuming $sum['cur']
and $sum['max']
are numeric, it doesn't matter whether they're numeric strings or actual numbers. PHP will automatically convert them to the necessary type when you try to do math operations on them or compare them to numbers.
$percentage = 0.7;
if ($sum['cur'] / $sum['max'] >= $percentage) {
print ("Attention");
} else {
print ("OK");
};
If you need to display the actual percentage, you can calculate it beforehand rather than in the condition so that it can be used in the printed message. Since you're doing division, you may end up with some long decimal portion in the result. You can use printf
to format that as needed.
$threshold = 70;
$percentage = $sum['cur'] / $sum['max'] * 100;
if ($percentage >= $threshold) {
printf("Attention: %d%% percent are in use", $percentage);
} else {
echo "OK";
};
Upvotes: 3