Write a program to calculate Electricity bill in PHP

Description:

You need to write a PHP program to calculate electricity bill using if-else conditions.

Conditions:

  • For first 50 units – Rs. 3.50/unit
  • For next 100 units – Rs. 4.00/unit
  • For next 100 units – Rs. 5.20/unit
  • For units above 250 – Rs. 6.50/unit
  • You can use conditional statements.

View Solution/Program

<!DOCTYPE html>
 
<head>
	<title>PHP - Calculate Electricity Bill</title>
</head>
 
<?php
$result_str = $result = '';
if (isset($_POST['unit-submit'])) {
    $units = $_POST['units'];
    if (!empty($units)) {
        $result = calculate_bill($units);
        $result_str = 'Total amount of ' . $units . ' - ' . $result;
    }
}
/**
 * To calculate electricity bill as per unit cost
 */
function calculate_bill($units) {
    $unit_cost_first = 3.50;
    $unit_cost_second = 4.00;
    $unit_cost_third = 5.20;
    $unit_cost_fourth = 6.50;
 
    if($units <= 50) {
        $bill = $units * $unit_cost_first;
    }
    else if($units > 50 && $units <= 100) {
        $temp = 50 * $unit_cost_first;
        $remaining_units = $units - 50;
        $bill = $temp + ($remaining_units * $unit_cost_second);
    }
    else if($units > 100 && $units <= 200) {
        $temp = (50 * 3.5) + (100 * $unit_cost_second);
        $remaining_units = $units - 150;
        $bill = $temp + ($remaining_units * $unit_cost_third);
    }
    else {
        $temp = (50 * 3.5) + (100 * $unit_cost_second) + (100 * $unit_cost_third);
        $remaining_units = $units - 250;
        $bill = $temp + ($remaining_units * $unit_cost_fourth);
    }
    return number_format((float)$bill, 2, '.', '');
}
 
?>
 
<body>
	<div id="page-wrap">
		<h1>Php - Calculate Electricity Bill</h1>
		
		<form action="" method="post" id="quiz-form">            
            	<input type="number" name="units" id="units" placeholder="Please enter no. of Units" />            
            	<input type="submit" name="unit-submit" id="unit-submit" value="Submit" />		
		</form>
 
		<div>
		    <?php echo '<br />' . $result_str; ?>
		</div>	
	</div>
</body>
</html>
Tutorials Class - Output Window


Learn more about the similar topics:
Tutorials
PHP Decision Making
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
Interview Questions & Answers
No Content Found.