'Is there a simple way to rewrite the PHP code attached (using arrays as a lookup table perhaps)?

switch ($hiBid) {
case ($hiBid > 0 && $hiBid <= 1):
    $minIncrement = .01;
    break;
case ($hiBid > 1 && $hiBid <= 5):
    $minIncrement = .25;
    break;
case ($hiBid > 5 && $hiBid <= 25):
    $minIncrement = 1;
    break;
case ($hiBid > 25 && $hiBid <= 100):
    $minIncrement = 5;
    break;    
case ($hiBid > 100 && $hiBid <= 500):
    $minIncrement = 10;
    break;
case ($hiBid > 500 && $hiBid <= 1000):
    $minIncrement = 25;
    break;
}

Looking for way to simplify this code more like a database lookup table, primarily to allow many more range comparisons that will be easier to read like a spreadsheet, where they will be initially defined.



Solution 1:[1]

Every time you find yourself writing repetitive code like this you can probably re-envision it as a loop and an array.

function getIncrement($bid, $tholds, $min=0) {
    $max = max(array_keys($tholds));
    if( $bid <= $min || $bid > $max ) {
        throw new \Exception("Bid outside threshold range");
    }
    
    $prev = $min;
    foreach( $tholds as $thold => $increment ) {
        if( $bid > $prev && $bid <= $thold ) {
            return $increment;
        }
        $prev = $thold;
    }
}

$tholds = [
       1 =>  0.01,
       5 =>  0.25,
      25 =>  1.00,
     100 =>  5.00,
     500 => 10.00,
    1000 => 25.00
];

var_dump(getIncrement(256, $tholds));

Ouput:

float(10)

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 Sammitch