PHP All Exercises & Assignments

All 31 PHP exercises in one list: variables and echo, operators, if/else and switch, loops, strings, arrays, functions and a MySQL table.

Write a program to count 5 to 15 using PHP loop

Description: Write a PHP program to display the numbers from 5 to 15, one number in each line, using a PHP loop.

Rules and hints:

  • Use a for or a while loop.
  • Use a variable for the counter.
  • Use the HTML tag <br> for the line break.

PHP program to count 5 to 15 using a while loop

<?php
$count = 5;

while ($count <= 15) {
    echo $count . "<br>";
    $count++;
}
?>

Output:

Tutorials Class - Output Window

5
6
7
8
9
10
11
12
13
14
15

The same with a for loop

<?php
for ($count = 5; $count <= 15; $count++) {
    echo $count . "<br>";
}
?>

How it works

  • The counter starts at 5. The loop runs while the counter is 15 or less.
  • $count++ adds 1 in every round, so the loop ends after 15.

Write a program to print “Hello World” using echo

Description: Write a PHP program to print “Hello World” using echo only.

Rules and hints:

  • You can not use any variable.
  • End every statement with a semicolon.

PHP program to print Hello World

<?php
echo "Hello World";
?>

Output:

Tutorials Class - Output Window

Hello World

How it works

  • <?php and ?> are the PHP tags.
  • echo prints the text on the page.
  • The text is in double quotes, and the statement ends with ;.

Related: PHP Syntax and echo vs print.

Write a program to print “Hello PHP” using variable

Description: Write a PHP program to print “Hello PHP” using a variable.

Rules and hints:

  • You can not write the text directly in echo.
  • Store the text in a variable first, and then print the variable.

PHP program to print Hello PHP using a variable

<?php
$message = "Hello PHP";

echo $message;
?>

Output:

Tutorials Class - Output Window

Hello PHP

How it works

  • $message is a variable that stores the text.
  • echo $message; prints the value of the variable.

Related: PHP Variables.

Write a program to print a string using echo+variable.

Description: Write a PHP program to print “Welcome to the PHP World”. Keep a part of the text in a variable, and write the other part directly in echo.

Rules and hints:

  • Use a variable that contains the string “PHP World”.
  • Join the variable with the rest of the text using the dot (.) operator.

PHP program to print a text using echo and a variable

<?php
$world = "PHP World";

echo "Welcome to the " . $world;
?>

Output:

Tutorials Class - Output Window

Welcome to the PHP World

How it works

  • The dot operator joins the text with the variable.
  • You can also write echo "Welcome to the $world";. Variables inside double quotes are replaced by their values.

Related: How to concatenate two strings in PHP.

Write a program to print two variables in single echo

Description: Write a PHP program to print two variables using only one echo statement.

Rules and hints:

  • The first variable has the text “Good Morning.”
  • The second variable has the text “Have a nice day!”
  • The output must be: Good Morning. Have a nice day!
  • You can use only one echo statement.

PHP program to print two variables in a single echo

<?php
$first = "Good Morning.";
$second = "Have a nice day!";

echo $first . " " . $second;
?>

Output:

Tutorials Class - Output Window

Good Morning. Have a nice day!

How it works

  • The dot operator joins the two variables, and a space in quotes is added between them.
  • Another way is the comma: echo $first, " ", $second;.

See three ways to print many variables in one echo.

Write a program to check student grade based on marks

Description: Write a PHP program to find the grade of a student based on the marks, using the if-else statement.

Rules and hints:

  • If marks are 60 or more, the grade is First Division.
  • If marks are from 45 to 59, the grade is Second Division.
  • If marks are from 33 to 44, the grade is Third Division.
  • If marks are less than 33, the student is Fail.

PHP program to check the grade of a student

<?php
$marks = 72;

if ($marks >= 60) {
    $grade = "First Division";
} elseif ($marks >= 45) {
    $grade = "Second Division";
} elseif ($marks >= 33) {
    $grade = "Third Division";
} else {
    $grade = "Fail";
}

echo "Student grade: " . $grade;
?>

Output:

Tutorials Class - Output Window

Student grade: First Division

How it works

  • PHP checks the conditions from top to bottom and runs only the first one that is true.
  • So it is enough to write the lowest marks of each grade (60, 45, 33) in the conditions.
  • Change $marks to 40 and 20 and run again to test the other grades.

Write a program to show day of the week using switch

Description: Write a PHP program to show the day of the week (for example Monday) based on a number, using the switch statement.

Rules and hints:

  • The number can be from 1 to 7. Number 1 is Monday.
  • If the number is not between 1 and 7, show an invalid number message in the default case.

PHP program to show the day of the week using switch

<?php
$day = 5;

switch ($day) {
    case 1:
        echo "It is Monday!";
        break;
    case 2:
        echo "It is Tuesday!";
        break;
    case 3:
        echo "It is Wednesday!";
        break;
    case 4:
        echo "It is Thursday!";
        break;
    case 5:
        echo "It is Friday!";
        break;
    case 6:
        echo "It is Saturday!";
        break;
    case 7:
        echo "It is Sunday!";
        break;
    default:
        echo "Invalid number. Enter a number from 1 to 7.";
}
?>

Output:

Tutorials Class - Output Window

It is Friday!

How it works

  • switch compares $day with every case.
  • break stops the switch after a match. Without it PHP would run the next cases too.
  • default runs when no case matches.

The same with the PHP 8 match expression is in PHP match Expression.

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.

Factorial program in PHP using recursive function

Description: Write a PHP program to find the factorial of a number using a recursive function.

What is a recursive function? A recursive function is a function that calls itself, until a stopping condition is reached.


PHP program for factorial using recursion

<?php
function factorial($n) {
    if ($n <= 1) {
        return 1;           // stopping condition
    }

    return $n * factorial($n - 1);
}

echo factorial(4) . "<br>";
echo factorial(5);
?>

Output:

Tutorials Class - Output Window

24
120

How it works

  • factorial(4) returns 4 x factorial(3), then 3 x factorial(2), then 2 x factorial(1).
  • When $n is 1 or less the function returns 1 and stops. Without this condition the function would call itself for ever.
  • The results come back one by one: 1, then 2, then 6, then 24.

Compare it with the loop solution: factorial using a for loop.

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 create given pattern with * using for loop

Description: Write a PHP program to print this pattern using loops:

*
**
***
****
*****
******
*******
********

Rules and hints:

  • You can use a for or a while loop.
  • Use a nested loop (a loop inside a loop).

PHP program to print the star pattern using two for loops

<?php
for ($row = 1; $row <= 8; $row++) {
    for ($star = 1; $star <= $row; $star++) {
        echo "*";
    }
    echo "<br>";
}
?>

Output:

Tutorials Class - Output Window

*
**
***
****
*****
******
*******
********

How it works

  • The outer loop makes 8 rows.
  • The inner loop prints as many stars as the number of the current row (1 star in row 1, 2 stars in row 2, and so on).
  • After every row, <br> moves to the next line.

Shorter version

<?php
for ($row = 1; $row <= 8; $row++) {
    echo str_repeat("*", $row) . "<br>";
}
?>

Simple Tips for PHP Beginners

When you start PHP programming, you will get syntax errors. Many of them are small mistakes, but they can take a lot of time to find if you are not familiar with the basic syntax. These simple tips will save your time.


Habits that help

  • Type the code yourself. Copy and paste is fast, but you will not learn the syntax. Typing builds the habit.
  • Start small. Write and run a few lines at a time, so you know which line has the problem.
  • Read the error message. It tells the file and the line number. The real mistake is often on the line above.
  • Show errors on your local computer. Use error_reporting(E_ALL); while learning. Read PHP Errors.
  • Use a good editor. Visual Studio Code highlights the code and shows missing brackets.
  • Write comments and indent your code. It makes the code easy to read and to fix. See PHP Comments.
  • Practice every day, even 30 minutes. Try the PHP exercises.

Common beginner mistakes

MistakeExampleFix
Missing semicolonecho "Hi"End every statement with ;
Brackets or quotes not closedecho "Hi;Check that every (, { and quote has its pair
Wrong variable case$Name and $nameVariable names are case-sensitive. See PHP Variables
Missing dollar signname = "Robin";Variables start with $
Using = for comparisonif ($a = 5)Use == or === to compare
Opening the file directlyDouble click on the fileRun it with http://localhost. See PHP Installation
Note: Do not worry about errors. Every developer sees them every day. Fixing them is the best way to learn.

Experiment with Basic PHP Syntax Errors

When you start PHP, you will see errors. They stop your program, and sometimes a small mistake takes a long time to find. A good way to get friendly with them is to make the mistakes yourself and see the message. Then you will know them when they come in real work.


A working program

<?php
echo "Hello World!";
?>

Output:

Tutorials Class - Output Window

Hello World!

Now we will break this program in different ways. Run each example on your local computer and read the message. The file name and line number in your messages will be different.


Experiment 1: missing semicolon

<?php
echo "Hello"
echo " World";
?>
Tutorials Class - Output Window

Parse error: syntax error, unexpected token “echo”, expecting “,” or “;” in /path/index.php on line 3

PHP reports the line after the missing semicolon, because it only understands the problem when it reads the next statement.

Experiment 2: undefined variable

<?php
$name = "Robin";
echo $nme;     // typing mistake
?>
Tutorials Class - Output Window

Warning: Undefined variable $nme in /path/index.php on line 3

This is only a warning, so the script goes on. The cause is a typing mistake, or the different case of the variable name.

Experiment 3: unknown function

<?php
printt("Hello");
?>
Tutorials Class - Output Window

Fatal error: Uncaught Error: Call to undefined function printt()

Experiment 4: bracket not closed

<?php
if (true) {
    echo "Yes";
?>
Tutorials Class - Output Window

Parse error: Unclosed ‘{‘ on line 2

Experiment 5: divide by zero

<?php
echo 10 / 0;
?>
Tutorials Class - Output Window

Fatal error: Uncaught DivisionByZeroError: Division by zero


What to learn from it

  • Parse errors are syntax mistakes. The program does not start at all.
  • Warnings and notices do not stop the program, but they show a problem to fix.
  • Fatal errors stop the program in the middle.

See all types of errors in PHP Errors and the types of errors in PHP.

Using phpinfo() – Display PHP Configuration & Modules

phpinfo() is a built-in PHP function that shows a full page of information about your PHP: the version, the configuration file in use, the settings and the loaded modules (extensions).

When PHP is installed, many extensions come with it. Some are enabled and some are not. Extensions add features to PHP. For example, the date extension gives date and time functions, mysqli is used to connect with MySQL, and curl is used for APIs. It is good to look at them.


Example using phpinfo()

<?php
phpinfo();
?>

Save it as info.php in your project folder, and open it with http://localhost/info.php. You will see a long page with many tables.

What you can find on that page

  • The PHP version and the system where it runs.
  • The path of the loaded php.ini file, so you know which file to edit.
  • Settings like upload_max_filesize and max_execution_time.
  • The list of all loaded extensions, like mysqli, curl and mbstring.
Note: Security: The phpinfo page shows private details about your server. Never leave such a file on a live website. Delete it after you check what you need.

Other ways to check

<?php
echo "PHP version: " . PHP_VERSION . "<br>";
var_dump(extension_loaded("mysqli"));
echo ini_get("upload_max_filesize");
?>

Output:

Sample output, yours can be different

PHP version: 8.2.12
bool(true)
2M

  • PHP_VERSION gives the version.
  • extension_loaded("name") tells if an extension is on.
  • ini_get() reads one setting.
  • In the command line, php -v, php -m (modules) and php -i (same as phpinfo) work.

Related: PHP Installation.

Write a PHP program to add two numbers

Description: Write a PHP program to find the sum (addition) of two numbers.

Rules and hints:


PHP program to add two numbers

<?php
$first = 15;
$second = 10;

$sum = $first + $second;

echo "Result: " . $sum;
?>

Output:

Tutorials Class - Output Window

Result: 25

How it works

  • The two numbers are stored in $first and $second.
  • The result of the addition is stored in $sum and printed.

Try this too

  • Change the program to subtract, multiply and divide the numbers.
  • Take the numbers from an HTML form using $_POST. See PHP Forms Handling.

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.

Remove specific element by value from an array in PHP?

Description: Write a PHP program to remove a specific element, by its value, from an array.

Rules and hints:

  • Take an array with the names of some months.
  • Take a variable with the value that you want to remove.
  • You can use array functions or a foreach loop.

Solution 1: array_search() and unset()

array_search() finds the key of the value, and unset() removes that key. The other keys are not changed.

<?php
$months = ["January", "February", "March", "April", "May"];
$remove = "March";

$key = array_search($remove, $months);

if ($key !== false) {
    unset($months[$key]);
}

print_r($months);
?>

Output:

Tutorials Class - Output Window

Array
(
[0] => January
[1] => February
[3] => April
[4] => May
)

Solution 2: array_diff()

array_diff() removes all matching values (also if the value is many times in the array). Use array_values() to get new keys 0, 1, 2…

<?php
$months = ["January", "February", "March", "April", "May"];
$remove = "March";

$months = array_values(array_diff($months, [$remove]));

echo implode(", ", $months);
?>

Output:

Tutorials Class - Output Window

January, February, April, May

Solution 3: array_filter()

<?php
$months = ["January", "February", "March", "April", "May"];
$remove = "March";

$months = array_filter($months, fn($month) => $month !== $remove);

echo implode(", ", $months);
?>

Output:

Tutorials Class - Output Window

January, February, April, May

Note that solution 1 removes only the first match, but solutions 2 and 3 remove every match.

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 calculate area of rectangle

Description: Write a PHP program to calculate the area of a rectangle using a PHP function.

Rules and hints:

  • You must use a function.
  • The function should have two arguments: length and width.

PHP program to calculate the area of a rectangle

<?php
function rectArea($length, $width) {
    return $length * $width;
}

$length = 2;
$width = 4;

echo "Area of rectangle with length " . $length . " and width " . $width . " is " . rectArea($length, $width);
?>

Output:

Tutorials Class - Output Window

Area of rectangle with length 2 and width 4 is 8

How it works

  • The function multiplies the length with the width and returns the result.
  • We print the text and the returned value together with the dot operator.

Try this too

  • Give default values to the parameters, like function rectArea($length = 2, $width = 4), and call it without arguments.
  • Write a similar function for the area of a circle using M_PI.