parliesty
parliesty

Reputation: 17

How to calculate total cost based on price ranges of items

I need to calculate total cost of items, based on ranges:

    if ($itemCount <11)
        {
    $cost_for_range = 1;
        }
    if ($itemCount <26 && $itemCount >=11)
    {
        $cost_for_range = 0.75;
    }
    if ($itemCount <50 && $itemCount >=26)
    {
        $cost_for_range = 0.55;
    }

Thing is - I need to count final cost taking earlier levels into consideration - eg if the cart has 30 items, the price would be:

Upvotes: 0

Views: 277

Answers (3)

jspit
jspit

Reputation: 7703

For a universal solution, it is good to define the discounts in an array. This solution is then ready for extensions and changes.

$rebate = [10 => 1.0, 15 => 0.75, PHP_INT_MAX => 0.55];

The number and the discount array are transferred to the function that calculates the cost factor. The calculation itself is realized with a simple forech loop with termination condition.

function calcCostFactor(int $count, array $rebate){
  $factor = 0.0;
  foreach($rebate as $number => $val){
    $factor += min($count,$number) * $val;
    $count -= $number;
    if($count <=  0) break;
  }
  return $factor;
}

example:

$factor = calcCostFactor(30, $rebate);

Try it self.

Upvotes: 1

Nigel Ren
Nigel Ren

Reputation: 57121

Having some fun using min and max to do the various ranges...

function calculateCost ( int $count, float $cost )  {
    $total = min(10, $count) * $cost;
    $total += (min(15, max(0, $count - 10)) * ($cost * 0.75));
    $total += (max(0, $count - 25) * ($cost * 0.55));
    return $total;
}

the second calculation uses max(0, $count - 10), so this takes the first 10 off, but ensures it doesn't go negative. Then it uses the min(15, max(0, $count - 10)) to take the lowest of 15 or the number left (so with 30, this will be 15).

The last one is just the max of the count - 25 or 0, so for 30, this is 5.

Use it with...

echo calculateCOst( 30, 1 );

gives 24

Upvotes: 2

Yoleth
Yoleth

Reputation: 1272

Try this :

$itemCount = 25;
$total = 0;

for ( $i = 0 ; $i < $itemCount ; $i++ ) {
    if ( $i < 10 ) {
        $total += 1;
    } else if ( $i < 25 ) {
        $total += 0.75;
    } else if ( $i < 50 ) {
        $total += 0.55;
    } else {
        $total += 0; // price if more than 50
    }
}

Upvotes: 2

Related Questions