PHP Top Exercises

List of Top PHP Exercise & Assignment for Students. These best & popular exercises help you to understand different logics of PHP Programming. Practice Exercises for PHP Loops, Arrays, Functions, Decision Making, File Handling, Forms & Database Handling.

Write a factorial program using for loop in php

Description: Write a PHP program to calculate the factorial of a number using a for loop.

Rules and hints:

  • Factorial of 5 is 5 x 4 x 3 x 2 x 1 = 120.
  • Use a loop that multiplies the numbers one by one.

PHP program for factorial using a for loop

<?php
$num = 5;
$factorial = 1;

for ($x = $num; $x >= 1; $x--) {
    $factorial = $factorial * $x;
}

echo "The factorial of " . $num . " is " . $factorial;
?>

Output:

Tutorials Class - Output Window

The factorial of 5 is 120

How it works

  • $factorial starts with 1.
  • The loop goes from 5 down to 1, and multiplies $factorial with each number.
  • The factorial of 0 is 1, and this program gives 1 for it too, because the loop does not run.

Another way is to use a function that calls itself: factorial using recursion.

Write a program to create Chess board in PHP using for loop

Description: Write a PHP program that creates a chess board using nested for loops.

Rules and hints:

  • Use an HTML table. Make each square 50px wide and 50px high.
  • The squares must be black and white, one after the other.
  • Hint: if the sum of the row number and the column number is even, use white, otherwise black.

PHP program to create a chess board

<?php
echo '<table border="1" cellspacing="0" cellpadding="0">';

for ($row = 1; $row <= 8; $row++) {
    echo "<tr>";

    for ($col = 1; $col <= 8; $col++) {
        $color = (($row + $col) % 2 == 0) ? "white" : "black";
        echo '<td style="width:50px;height:50px;background:' . $color . '"></td>';
    }

    echo "</tr>";
}

echo "</table>";
?>

Output:

Tutorials Class - Output Window

An 8 x 8 table of black and white squares, like a chess board

How it works

  • The outer loop creates the 8 rows (<tr>), and the inner loop creates 8 cells (<td>) in every row.
  • ($row + $col) % 2 is 0 for every second square, so the colors change like on a real chess board.
  • The ternary operator picks the color. See PHP Ternary Operator.

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 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.