PHP Decision Making

PHP decision making exercises: print numbers with conditions, positive or negative number, voting eligibility, a calculator with switch and an electricity bill program.

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.

Write a simple calculator program in PHP using switch case

Description: Write a simple calculator program in PHP using the switch case.

Rules and hints:

  • Operations: addition, subtraction, multiplication and division.
  • Use an HTML form with two number fields and a select box for the operation.
  • Check that both values are numbers, and do not allow division by zero.

PHP simple calculator program

<?php
$result = "";

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $first = $_POST["first_num"] ?? "";
    $second = $_POST["second_num"] ?? "";
    $operator = $_POST["operator"] ?? "";

    if (is_numeric($first) && is_numeric($second)) {
        switch ($operator) {
            case "Add":
                $result = $first + $second;
                break;
            case "Subtract":
                $result = $first - $second;
                break;
            case "Multiply":
                $result = $first * $second;
                break;
            case "Divide":
                $result = ($second == 0) ? "Cannot divide by zero" : $first / $second;
                break;
            default:
                $result = "Please select an operation";
        }
    } else {
        $result = "Please enter valid numbers";
    }
}
?>
<form method="post">
    <input type="text" name="first_num" value="<?php echo htmlspecialchars($_POST["first_num"] ?? ""); ?>">
    <select name="operator">
        <option>Add</option>
        <option>Subtract</option>
        <option>Multiply</option>
        <option>Divide</option>
    </select>
    <input type="text" name="second_num" value="<?php echo htmlspecialchars($_POST["second_num"] ?? ""); ?>">
    <button type="submit">Calculate</button>
</form>
<?php
if ($result !== "") {
    echo "<p>Result: " . htmlspecialchars((string) $result) . "</p>";
}
?>

Output:

When the numbers are 12 and 4 and the operation is Multiply

Result: 48

How it works

  • The PHP code at the top runs only when the form is sent with POST.
  • is_numeric() checks both values before the calculation.
  • switch selects the operation using the text of the select box.
  • The old values are put back in the fields, and htmlspecialchars() keeps the page safe from XSS.

Related: PHP Forms Handling.

Write a PHP program to check if a person is eligible to vote

Description: Write a PHP program to check if a person is eligible to vote or not.

Rules and hints:


PHP program to check voting eligibility

<?php
function checkVote($name, $age) {
    if ($age >= 18) {
        return $name . ", you are eligible to vote.";
    }

    return $name . ", you are not eligible to vote.";
}

echo checkVote("Rakesh", 19) . "<br>";
echo checkVote("Anita", 16);
?>

Output:

Tutorials Class - Output Window

Rakesh, you are eligible to vote.
Anita, you are not eligible to vote.

How it works

  • The function gets the name and the age as parameters.
  • If the age is 18 or more it returns the eligible message, otherwise the other message.
  • We call it two times with different values.

Write a PHP program to check whether a number is positive, negative or zero

Description: Write a PHP program to check whether a number is positive, negative or zero.

Rules and hints:

  • Use if else conditions.
  • Use the correct PHP operators.
  • Also check that the value is a number.
  • Write the logic in a function, so you can test many values.

PHP program to check a positive, negative or zero number

<?php
function checkNumber($number) {
    if (!is_numeric($number)) {
        return "Please enter a number";
    }

    if ($number > 0) {
        return $number . " is a positive number";
    } elseif ($number < 0) {
        return $number . " is a negative number";
    }

    return "The number is zero";
}

echo checkNumber(324) . "<br>";
echo checkNumber(-15) . "<br>";
echo checkNumber(0) . "<br>";
echo checkNumber("abc");
?>

Output:

Tutorials Class - Output Window

324 is a positive number
-15 is a negative number
The number is zero
Please enter a number

How it works

  • is_numeric() checks that the value is a number, so text like “abc” is rejected first.
  • If the number is bigger than 0 it is positive, if it is smaller than 0 it is negative. The only remaining case is zero.
  • Because it is a function, you can call it with different values.

Write a PHP Program to print 5 to 15 using Conditional statements

Description: Write a PHP program to print the numbers from 5 to 15 using conditional statements, without using any loop.

Rules and hints:

  • You can use a function with arguments.
  • You can not use a loop (for, while, foreach).
  • You can use if conditions.

PHP program to print 5 to 15 without a loop

<?php
function printNumbers($current, $end) {
    if ($current > $end) {
        return;                       // stop
    }

    echo $current . "<br>";
    printNumbers($current + 1, $end); // call the function again
}

printNumbers(5, 15);
?>

Output:

Tutorials Class - Output Window

5
6
7
8
9
10
11
12
13
14
15

How it works

  • The function prints the current number, and then calls itself with the next number.
  • When the current number becomes bigger than the end number, the if condition stops the function. This is called recursion.

Read about PHP functions and see another example of recursion in factorial using recursion.