I wrote a simple script with many conditions:
$item =12;
if($item < 5)
{
//display icon buyer
}
elseif ($item < 10)
{
//display icon buyer
}
elseif ($item < 15)
{
//display icon good buyer
}
elseif ($item < 20)
{
//display icon top buyer
}
// etc....
It's a long multi condition and I know is very bad.
How I could optimize the code?
Note. switch
is not possible because I'm using the operators <
and >
, etc.
Better than a bunch of conditionals is to look for a pattern that allows to just calculate it.
In your case it looks like that are steps by 5 - so appropriate for division.
Or map it:
$item = 12;
$icons = [
10 => 'buyer',
15 => 'good buyer',
20 => 'top buyer',
];
foreach ($icons as $value => $icon) {
if ($item < $value) {
return $icon;
}
}
return null;
Which allows more flexible steps (as you have it in your data in question).
Give this a go (demo):
<?php
function icon($item) {
$icons = array(
'buyer',
'buyer',
'good buyer',
'top buyer'
);
$index = max(0, min(3, $item / 5));
return $icons[$index];
}
$item = 12;
echo icon($item) . "\n";
$item = 1;
echo icon($item) . "\n";
$item = 100;
echo icon($item) . "\n";
Simply add to the $icons
array for more options / icons.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With