Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

multi-condition php

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.

like image 795
Kate Avatar asked Dec 25 '12 22:12

Kate


2 Answers

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).

like image 103
hakre Avatar answered Oct 16 '22 07:10

hakre


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.

like image 9
uınbɐɥs Avatar answered Oct 16 '22 08:10

uınbɐɥs