'Show different output depending on if value is greater than, less than, or equal to zero
I am fetching an integer value from my database which might be positive, negative, or zero.
I want to show an icon depending on the values relation to zero using FontAwesome's font icons.
- If the result
> 0, I want to show the result withicon-caret-up. - If the result
= 0, I want to show the result withicon-caret-right. - If the result
< 0, I want to show the result withicon-caret-down.
So I added the following php code :
$reponse=mysql_query("My SQL Query");
if ($reponse > 0) {
echo "<h1 class=\"uk-text-center uk-margin-bottom-remove\">".(mysql_result($reponse, 0))."<i class=\"uk-icon-caret-up\"></i></h1>";
}
elseif ($reponse == 0) {
echo "<h1 class=\"uk-text-center uk-margin-bottom-remove\">".(mysql_result($reponse, 0))."<i class=\"uk-icon-caret-up\"></i></h1>";
}
else {
echo "<h1 class=\"uk-text-center uk-margin-bottom-remove\">".(mysql_result($reponse, 0))."<i class=\"uk-icon-caret-down\"></i></h1>";
}
Whatever the result, even when it's a negative figure or equal to zero, I got only the first choice displaying the icon-caret-up.
Solution 1:[1]
Rather than a condition block, perhaps establish a lookup array for your three-way comparison. The spaceship operator can only return -1, 0, or 1, so your lookup just needs to translate those integers into words.
To avoid messy concatenation/interpolation, you can use placeholders in a template string and call upon printf() to display your content.
Code: (Demo)
$lookup = [
-1 => 'down',
0 => 'right',
1 => 'up',
];
foreach ([13, 0, -5] as $amount) {
printf(
'<h1 class="uk-text-center uk-margin-bottom-remove">
%s
<i class="uk-icon-caret-%s"></i>
</h1>',
$amount,
$lookup[$amount <=> 0]
);
echo "\n---\n";
}
Output:
<h1 class="uk-text-center uk-margin-bottom-remove">13<i class="uk-icon-caret-up"></i></h1>
---
<h1 class="uk-text-center uk-margin-bottom-remove">0<i class="uk-icon-caret-right"></i></h1>
---
<h1 class="uk-text-center uk-margin-bottom-remove">-5<i class="uk-icon-caret-down"></i></h1>
---
Since the spaceship operator is limited to 3 different return values, your lookup will need to maintain its current size (no room for contraction/expansion). This means that you can, if to your taste, directly write the lookup payload into the third parameter of printf() without declaring $lookup ... I realize some devs will consider this less attractive/readable.
printf(
'<h1 class="uk-text-center uk-margin-bottom-remove">
%s
<i class="uk-icon-caret-%s"></i>
</h1>',
$amount,
[-1 => 'down', 0 => 'right', 1 => 'up'][$amount <=> 0]
);
In PHP8, you may find match() to a worthwhile technique -- it will keep your code concise and allow you to easily modify your translations beyond exactly 3 words.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | mickmackusa |
