php - Slab wise electricity bill calculation in Yii2

one text

Solution:

So you simply want to multiply the amount covered by each slab (“units”) with the rate then - so I would create an array that has the slab end as key, and the rate as value - then you can simply loop over that with the extended foreach syntax, and have access to the rate corresponding to the slab at all times.

Expanding on my answer to the previous question, this would look like this then:

$input = '128.82';
$slabs = [100 => 10, 150 => 12, PHP_INT_MAX => 14];

$result = [];
$bill = 0;
$previous_slab = 0;

foreach($slabs as $slab => $rate) {
  // calculate distance between current and previous slab
  $slab_distance = $slab - $previous_slab;
  // if current remainder of input value is >= distance, add distance to result,
  // and subtract distance from remainder of input
  if( $input >= $slab_distance ) {
    $result[] = $slab_distance;
    $bill += $slab_distance * $rate;
    $input -= $slab_distance;
  }
  // otherwise, add remainder as last item of result, and break out of the loop here
  else {
    $result[] = $input;
    $bill += $input * $rate;
    break;
  }
  $previous_slab = $slab;
}

var_dump($result, $bill);

Result:

array (size=2)
  0 => int 100
  1 => float 28.82

float 1345.84

My approach again uses only the upper slab boundaries here - you don’t have one in your last record from the database, so I am substituting PHP_INT_MAX here for that NULL value. Taking that into account, when you create that array from your database content, should be not challenge, I hope.

(If you only need the 1345.84 as result here, and not the array that shows the distribution accross the indivudual slabs, then you can just remove all lines that contain $result anywhere.)

Source