Write a program to calculate Electricity bill in PHP

Description: Write a PHP program to calculate the electricity bill using conditional statements.

UnitsRate per unit
First 50 unitsRs. 3.50
Next 100 units (51 to 150)Rs. 4.00
Next 100 units (151 to 250)Rs. 5.20
Above 250 unitsRs. 6.50

Rules and hints:

  • Calculate the bill for the units that fall in each slab.
  • Write the logic in a function that gets the units and returns the bill.
  • Show the amount with 2 decimal digits.

PHP program to calculate the electricity bill

<?php
function electricityBill($units) {
    $bill = 0;

    if ($units > 250) {
        $bill += ($units - 250) * 6.50;
        $units = 250;
    }
    if ($units > 150) {
        $bill += ($units - 150) * 5.20;
        $units = 150;
    }
    if ($units > 50) {
        $bill += ($units - 50) * 4.00;
        $units = 50;
    }
    $bill += $units * 3.50;

    return $bill;
}

echo "Bill for 320 units: Rs. " . number_format(electricityBill(320), 2) . "<br>";
echo "Bill for 120 units: Rs. " . number_format(electricityBill(120), 2);
?>

Output:

Tutorials Class - Output Window

Bill for 320 units: Rs. 1,550.00
Bill for 120 units: Rs. 455.00

How it works

  • The function starts from the highest slab. The units above 250 are charged at 6.50, and then they are removed from $units.
  • The same is done for the 151 to 250 slab and the 51 to 150 slab. The remaining units are charged at 3.50.
  • For 320 units: 70 x 6.50 + 100 x 5.20 + 100 x 4.00 + 50 x 3.50 = 1550.
  • number_format() shows the amount with 2 decimals and a thousands separator.

Learn more about the similar topics:
Tutorials
PHP Decision Making
PHP match Expression
Exercises & Assignments
Write a program to check student grade based on marks
Write a program to show day of the week using switch
Write a program to calculate Electricity bill in PHP
Write a simple calculator program in PHP using switch case
Write a PHP program to check if a person is eligible to vote
Write a PHP program to check whether a number is positive, negative or zero
Write a PHP Program to print 5 to 15 using Conditional statements
Interview Questions & Answers
No Content Found.