Darekdari / PHP Exercises

100 PHP Exercises and Solutions PDF for Beginners

Practice PHP the way it sticks: 100 beginner exercises in 10 topics, from variables and loops to forms, OOP and PHP MySQL, with corrected solutions you can copy, run and save as a PDF.

100 exercisesCorrected solutionsPHP + MySQLChecked 2 Dec 2026
01 / Start here

100 PHP Exercises and Solutions for Beginners

Reading about PHP is not the same as writing it. If you are looking for PHP exercises for beginners with solutions, this page gives you 100 exercises grouped in 10 topics. Each topic has 10 tasks that go from easy to a little harder, and the key ones come with corrected code.

It also works as a set of exercices PHP corrigés: the exercises cover everything a beginner needs before building a real site, including PHP and MySQL exercises (exercices PHP MySQL corrigés). You can keep the whole page as a PDF for offline practice (see the PDF section below).

Facts checked on 2 December 2026. The code targets PHP 8.x. Check the official PHP manual if a function or setting behaves differently on your server.
02 / Method

How to Practice These PHP Exercises

Try first

Spend at least 10 minutes on each exercise before opening the solution.

Type, do not paste

Typing the code builds muscle memory and helps you catch syntax errors.

Change it

After it works, change the input or add one feature. That is where you learn.

Pace yourself

Ten exercises a day finishes the set in ten days. One hour a day is fine too.

03 / Setup

Set Up PHP Before You Start

You need PHP installed. The easiest options are a local server package such as XAMPP, Laragon or MAMP, or PHP on the command line. Create a file called test.php, then run it in the terminal with php test.php, or place it in your server folder and open it in the browser. For the MySQL section you also need a MySQL or MariaDB database, which these packages include.

Topic 1

PHP Basics and Output: Exercises 1 to 10

  1. Print “Hello, World!” with echo.
  2. Print your name and age on two lines.
  3. Use print and echo and explain the difference.
  4. Print an HTML heading from PHP.
  5. Add a single-line and a multi-line comment.
  6. Print today’s date with date().
  7. Print text with a variable inside double quotes.
  8. Use printf to format a price with 2 decimals.
  9. Show a PHP value with var_dump.
  10. Mix PHP and HTML in one file.
exercise-01.php
<?php
echo "Hello, World!";

Variables and Operators: Exercises 11 to 20

  1. Declare variables of type string, int, float and bool.
  2. Swap two variables without a third one.
  3. Add, subtract, multiply and divide two numbers.
  4. Compute the remainder with %.
  5. Use ++ and -- on a counter.
  6. Compute the area of a circle with pi().
  7. Convert Celsius to Fahrenheit.
  8. Use a constant with define() and const.
  9. Check a variable type with gettype().
  10. Cast a string to an integer and back.
Topic 3

PHP Conditions (if, else, switch): Exercises 21 to 30

  1. Check if a number is even or odd.
  2. Find the largest of three numbers.
  3. Check if a number is positive, negative or zero.
  4. Check if a year is a leap year.
  5. Print a grade (A to F) from a score.
  6. Use switch to print the day name from 1 to 7.
  7. Check if a person can vote (age 18 or more).
  8. Check if a character is a vowel.
  9. Use the ternary operator and ??.
  10. Build a simple calculator with match.
exercise-21.php
<?php
$n = 7;
echo ($n % 2 === 0) ? "$n is even" : "$n is odd";
Topic 4

PHP Loops: Exercises 31 to 40

  1. Print numbers 1 to 10 with a for loop.
  2. Print the multiplication table of 5.
  3. Sum the numbers from 1 to 100.
  4. Calculate a factorial.
  5. Print the Fibonacci sequence.
  6. Solve FizzBuzz from 1 to 50.
  7. Check if a number is prime.
  8. Reverse a number with a while loop.
  9. Print a star triangle.
  10. Use break and continue.
exercise-36.php (FizzBuzz)
<?php
for ($i = 1; $i <= 50; $i++) {
    if ($i % 15 === 0)      echo "FizzBuzz\n";
    elseif ($i % 3 === 0)   echo "Fizz\n";
    elseif ($i % 5 === 0)   echo "Buzz\n";
    else                    echo $i . "\n";
}
exercise-34.php (factorial)
<?php
$n = 5;
$f = 1;
for ($i = 2; $i <= $n; $i++) {
    $f *= $i;
}
echo "$n! = $f";   // 120
Topic 5

PHP String Exercises: 41 to 50

  1. Get the length of a string with strlen().
  2. Convert text to upper and lower case.
  3. Reverse a string.
  4. Check if a word is a palindrome.
  5. Count the words in a sentence.
  6. Replace a word with str_replace().
  7. Find a substring with strpos().
  8. Capitalize the first letter of each word.
  9. Count vowels in a string.
  10. Remove spaces from both ends with trim().
exercise-44.php (palindrome)
<?php
$word = "level";
$clean = strtolower($word);
echo ($clean === strrev($clean)) ? "Palindrome" : "Not a palindrome";
Topic 6

PHP Array Exercises: 51 to 60

  1. Create an indexed array and print it with foreach.
  2. Create an associative array of a student.
  3. Find the largest and smallest values.
  4. Calculate the sum and average of an array.
  5. Sort an array in ascending and descending order.
  6. Remove duplicate values.
  7. Check if a value exists with in_array().
  8. Merge two arrays.
  9. Filter even numbers with array_filter().
  10. Build a multidimensional array (a small table).
exercise-53.php
<?php
$nums = [4, 9, 2, 15, 7];
echo "Max: " . max($nums) . "\n";
echo "Min: " . min($nums) . "\n";
echo "Average: " . array_sum($nums) / count($nums);
Topic 7

PHP Function Exercises: 61 to 70

  1. Write a function that adds two numbers.
  2. Use default parameter values.
  3. Return several values with an array.
  4. Write a recursive factorial function.
  5. Pass a variable by reference.
  6. Write an isPrime() function.
  7. Use type declarations and a return type.
  8. Write an anonymous function and an arrow function.
  9. Use array_map() with a callback.
  10. Use include and require for a function file.
exercise-66.php
<?php
function isPrime(int $n): bool {
    if ($n < 2) return false;
    for ($i = 2; $i * $i <= $n; $i++) {
        if ($n % $i === 0) return false;
    }
    return true;
}
var_dump(isPrime(29));   // bool(true)
Topic 8

PHP Forms, Sessions and Cookies: 71 to 80

  1. Build a form that sends data with POST.
  2. Read data with $_GET.
  3. Validate that a field is not empty.
  4. Validate an email with filter_var().
  5. Protect output with htmlspecialchars().
  6. Upload an image and check its type and size.
  7. Start a session and store a username.
  8. Build a simple login with a session.
  9. Set and read a cookie.
  10. Build a contact form with validation messages.
exercise-74.php
<?php
$msg = "";
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $email = trim($_POST["email"] ?? "");
    if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $msg = "Valid email: " . htmlspecialchars($email);
    } else {
        $msg = "Please enter a valid email.";
    }
}
?>
<form method="post">
  <input name="email" type="text">
  <button>Send</button>
</form>
<p><?= $msg ?></p>
Topic 9

PHP OOP Exercises: 81 to 90

  1. Create a class with properties and a method.
  2. Use a constructor to set values.
  3. Use private properties with getters and setters.
  4. Create a class that extends another one.
  5. Override a parent method.
  6. Use a static method and a class constant.
  7. Write an interface and implement it.
  8. Use an abstract class.
  9. Use a trait.
  10. Throw and catch a custom exception.
exercise-83.php
<?php
class Account {
    private float $balance = 0;

    public function deposit(float $amount): void {
        if ($amount <= 0) throw new InvalidArgumentException("Invalid amount");
        $this->balance += $amount;
    }
    public function getBalance(): float {
        return $this->balance;
    }
}

$a = new Account();
$a->deposit(50);
echo $a->getBalance();   // 50
Topic 10

PHP and MySQL Exercises with Solutions: 91 to 100

These are the exercices PHP MySQL corrigés that turn you from a beginner into someone who can build a small app. Create a database called school with a table students(id, name, email) first.

  1. Connect to MySQL with PDO.
  2. Create a table with PHP.
  3. Insert a row with a prepared statement.
  4. Select and display all rows in an HTML table.
  5. Select one row by ID.
  6. Update a row.
  7. Delete a row.
  8. Build a search form with LIKE.
  9. Add pagination with LIMIT and OFFSET.
  10. Build a small CRUD app (create, read, update, delete).
exercise-91-94.php
<?php
$pdo = new PDO(
    "mysql:host=localhost;dbname=school;charset=utf8mb4",
    "root", "",
    [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
);

// 93: insert with a prepared statement
$stmt = $pdo->prepare("INSERT INTO students (name, email) VALUES (?, ?)");
$stmt->execute(["Sara", "sara@example.com"]);

// 94: select and display
foreach ($pdo->query("SELECT id, name, email FROM students") as $row) {
    echo htmlspecialchars($row["name"]) . " - " . htmlspecialchars($row["email"]) . "<br>";
}
Always use prepared statements with user input. Never put $_POST values directly inside an SQL string. On a real server, use a dedicated database user and not root.
PDF

How to Get the 100 PHP Exercises as a PDF

To keep an offline copy of these PHP exercises and solutions in PDF, open this page, press Ctrl + P (or Cmd + P on Mac), choose Save as PDF as the printer and save. The page has a print-friendly layout so the code stays readable.

Printing a PDF is also a good way to practice away from the screen: solve the exercise on paper, then check it on your computer.

Avoid these

Common PHP Beginner Mistakes

Mistake

Missing semicolon

The most common syntax error. Read the line number in the message.

Mistake

Using = instead of ==

A single sign assigns. Use === to compare.

Mistake

Trusting user input

Validate it and escape output with htmlspecialchars().

Mistake

SQL in strings

Use prepared statements to prevent SQL injection.

Mistake

Copying solutions

You learn when you struggle first. Look at the answer last.

Tip

Turn on errors locally

Use error_reporting(E_ALL) while learning, and never on a live site.

Checklist

Your 100 PHP Exercises Progress

Tick each topic when you finish its 10 exercises.

0 of 10 done

En français

Exercices PHP Corrigés pour Débutants (PDF)

Vous cherchez des exercices PHP PDF, des exercices PHP corrigés ou des exercices PHP MySQL corrigés PDF ? Cette page propose 100 exercices PHP pour débutants, classés par thème : variables, conditions, boucles, chaînes, tableaux, fonctions, formulaires, POO et MySQL.

Chaque section contient des exercices et un corrigé de code que vous pouvez copier et tester. Pour obtenir un exercice PHP corrigé en PDF, utilisez la fonction « Imprimer » de votre navigateur et choisissez « Enregistrer au format PDF ». Pour pratiquer exercice PHP MySQL, rendez-vous à la section 10 et créez la base school.

FAQ

Frequently Asked Questions About PHP Exercises

Where can I find 100 PHP exercises and solutions in PDF?

This page lists 100 PHP exercises for beginners grouped in 10 topics, with corrected solutions for key exercises. Use your browser’s Print option and choose Save as PDF to keep an offline copy.

What are good PHP exercises for beginners with solutions?

Start with output and variables, then conditions, loops, strings, arrays and functions. Examples: even or odd, factorial, FizzBuzz, palindrome and the largest number in an array.

Are there PHP and MySQL exercises with corrections?

Yes. Section 10 contains PHP and MySQL exercises using PDO, including connecting to a database, inserting rows and reading them back, with corrected code.

How long does it take to finish 100 PHP exercises?

Most beginners need two to four weeks at one hour per day. Do 10 exercises per topic and write the code yourself before reading the solution.

Do I need to install anything to practice?

Yes. Install a local server such as XAMPP, Laragon or MAMP, or run PHP from the command line with php file.php. An online PHP sandbox also works for simple exercises.

Should I use mysqli or PDO for the MySQL exercises?

PDO is a good choice for beginners because it supports prepared statements and works with several databases. mysqli is also fine if you only use MySQL.

Quels sont les meilleurs exercices PHP corrigés pour débutants ?

Commencez par les variables, les conditions, les boucles et les tableaux, puis passez aux fonctions, aux formulaires et à PHP MySQL. Chaque section de cette page propose des exercices et des corrigés.

Conclusion

Practice a Little Every Day

One hundred exercises will not make you an expert, but they will make you comfortable with PHP syntax, arrays, functions, forms and MySQL. Do them in order, type every solution, and then build a small project such as a to-do list or a blog.

Want more? Explore PHP projects, Python exercises and programming tutorials on Darekdari.com.

Learn more

More info about us

Scroll to Top