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 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).
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.
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.
PHP Basics and Output: Exercises 1 to 10
- Print “Hello, World!” with
echo. - Print your name and age on two lines.
- Use
printandechoand explain the difference. - Print an HTML heading from PHP.
- Add a single-line and a multi-line comment.
- Print today’s date with
date(). - Print text with a variable inside double quotes.
- Use
printfto format a price with 2 decimals. - Show a PHP value with
var_dump. - Mix PHP and HTML in one file.
<?php
echo "Hello, World!";Variables and Operators: Exercises 11 to 20
- Declare variables of type string, int, float and bool.
- Swap two variables without a third one.
- Add, subtract, multiply and divide two numbers.
- Compute the remainder with
%. - Use
++and--on a counter. - Compute the area of a circle with
pi(). - Convert Celsius to Fahrenheit.
- Use a constant with
define()andconst. - Check a variable type with
gettype(). - Cast a string to an integer and back.
PHP Conditions (if, else, switch): Exercises 21 to 30
- Check if a number is even or odd.
- Find the largest of three numbers.
- Check if a number is positive, negative or zero.
- Check if a year is a leap year.
- Print a grade (A to F) from a score.
- Use
switchto print the day name from 1 to 7. - Check if a person can vote (age 18 or more).
- Check if a character is a vowel.
- Use the ternary operator and
??. - Build a simple calculator with
match.
<?php
$n = 7;
echo ($n % 2 === 0) ? "$n is even" : "$n is odd";PHP Loops: Exercises 31 to 40
- Print numbers 1 to 10 with a
forloop. - Print the multiplication table of 5.
- Sum the numbers from 1 to 100.
- Calculate a factorial.
- Print the Fibonacci sequence.
- Solve FizzBuzz from 1 to 50.
- Check if a number is prime.
- Reverse a number with a
whileloop. - Print a star triangle.
- Use
breakandcontinue.
<?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";
}<?php
$n = 5;
$f = 1;
for ($i = 2; $i <= $n; $i++) {
$f *= $i;
}
echo "$n! = $f"; // 120PHP String Exercises: 41 to 50
- Get the length of a string with
strlen(). - Convert text to upper and lower case.
- Reverse a string.
- Check if a word is a palindrome.
- Count the words in a sentence.
- Replace a word with
str_replace(). - Find a substring with
strpos(). - Capitalize the first letter of each word.
- Count vowels in a string.
- Remove spaces from both ends with
trim().
<?php
$word = "level";
$clean = strtolower($word);
echo ($clean === strrev($clean)) ? "Palindrome" : "Not a palindrome";PHP Array Exercises: 51 to 60
- Create an indexed array and print it with
foreach. - Create an associative array of a student.
- Find the largest and smallest values.
- Calculate the sum and average of an array.
- Sort an array in ascending and descending order.
- Remove duplicate values.
- Check if a value exists with
in_array(). - Merge two arrays.
- Filter even numbers with
array_filter(). - Build a multidimensional array (a small table).
<?php
$nums = [4, 9, 2, 15, 7];
echo "Max: " . max($nums) . "\n";
echo "Min: " . min($nums) . "\n";
echo "Average: " . array_sum($nums) / count($nums);PHP Function Exercises: 61 to 70
- Write a function that adds two numbers.
- Use default parameter values.
- Return several values with an array.
- Write a recursive factorial function.
- Pass a variable by reference.
- Write an
isPrime()function. - Use type declarations and a return type.
- Write an anonymous function and an arrow function.
- Use
array_map()with a callback. - Use
includeandrequirefor a function file.
<?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)PHP Forms, Sessions and Cookies: 71 to 80
- Build a form that sends data with
POST. - Read data with
$_GET. - Validate that a field is not empty.
- Validate an email with
filter_var(). - Protect output with
htmlspecialchars(). - Upload an image and check its type and size.
- Start a session and store a username.
- Build a simple login with a session.
- Set and read a cookie.
- Build a contact form with validation messages.
<?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>PHP OOP Exercises: 81 to 90
- Create a class with properties and a method.
- Use a constructor to set values.
- Use
privateproperties with getters and setters. - Create a class that extends another one.
- Override a parent method.
- Use a static method and a class constant.
- Write an interface and implement it.
- Use an abstract class.
- Use a trait.
- Throw and catch a custom exception.
<?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(); // 50PHP 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.
- Connect to MySQL with PDO.
- Create a table with PHP.
- Insert a row with a prepared statement.
- Select and display all rows in an HTML table.
- Select one row by ID.
- Update a row.
- Delete a row.
- Build a search form with
LIKE. - Add pagination with
LIMITandOFFSET. - Build a small CRUD app (create, read, update, delete).
<?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>";
}$_POST values directly inside an SQL string. On a real server, use a dedicated database user and not root.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.
Common PHP Beginner Mistakes
Missing semicolon
The most common syntax error. Read the line number in the message.
Using = instead of ==
A single sign assigns. Use === to compare.
Trusting user input
Validate it and escape output with htmlspecialchars().
SQL in strings
Use prepared statements to prevent SQL injection.
Copying solutions
You learn when you struggle first. Look at the answer last.
Turn on errors locally
Use error_reporting(E_ALL) while learning, and never on a live site.
Your 100 PHP Exercises Progress
Tick each topic when you finish its 10 exercises.
0 of 10 done
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.
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.
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.
