Last updated: April 4, 2026

Image: w3resource
How many PHP tutorials have you read where you understood every line, then sat down to write a script from scratch and found yourself staring at a blank file? Reading about PHP and practising PHP are two completely different things – and that gap is where most beginners quietly give up.
By the end of this article, you will be able to work through structured PHP basic exercises covering variables, operators, form handling, and real web tasks like detecting a visitor’s browser or redirecting pages. You will understand not just what each code snippet does, but why it works – and what to do when it does not.
Prerequisites
Before you start, make sure you have:
- A basic understanding of what PHP is (a server-side scripting language)
- Either a local environment (XAMPP, Laragon, or similar) or access to an in-browser PHP executor
- A code editor – VS Code with the right extensions can make PHP development considerably more comfortable
- No prior PHP exercise experience required – that is what this guide is for
Setting Up Your Local Environment
Running these examples locally takes about five minutes and gives you a realistic development workflow. Here is the quickest path:
Option 1 – XAMPP (Windows, macOS, Linux):
- Download XAMPP from apachefriends.org and run the installer.
- Start the Apache module from the XAMPP Control Panel.
- Place your PHP files inside
C:\xampp\htdocs\(Windows) or/Applications/XAMPP/htdocs/(macOS). - Open your browser and navigate to
http://localhost/yourfile.php.
Option 2 – PHP’s built-in server (if PHP is already installed):
cd /path/to/your/project
php -S localhost:8000
Then open http://localhost:8000/yourfile.php in your browser. If you see a blank page instead of output, add error_reporting(E_ALL); ini_set('display_errors', 1); at the top of your file to surface any hidden errors.
Option 3 – No installation at all: Resources like w3resource provide an in-browser code editor on each exercise page. This is the fastest way to start, though a local environment is recommended once you are working on anything beyond single-file examples.
Why PHP Basic Exercises Beat Passive Learning
Your brain does not retain syntax it has never typed. PHP basic exercises force you to retrieve information actively, make errors, and fix them – which is the actual mechanism of learning.
Resources like w3resource host collections of PHP practice problems, each with a worked solution and detailed explanation. The structure matters: it gives you a worked example to study, then immediately asks you to generalise it. That is spaced repetition built into the exercise design itself.
A common misconception is that exercises are only for beginners. In reality, even developers moving into PHP from JavaScript or Python use structured exercises to internalise the differences in syntax and behaviour. If you are coming from a JavaScript background, you might also want to read about Mastering ES2026 Features to see how the two languages are evolving in parallel.
What PHP Basic Exercises Actually Cover
The exercise topics are broader than most beginners expect. Here is a practical walkthrough of the core areas with working code you can run immediately.
1. Variables and String Handling
Step 1: Declare and output a variable.
<?php
$greeting = "Hello, World!";
echo $greeting;
?>
Expected output: Hello, World!
PHP variables start with $ – forgetting that is the single most common mistake beginners make when coming from another language.
Common mistake: Writing greeting = "Hello"; without the $ prefix produces Parse error: syntax error, unexpected token. If you see this error, check every variable name in that block for a missing $.
Step 2: Use escape characters in strings.
<?php
$quote = "She said, \"PHP is straightforward once you practise.\"";
echo $quote;
?>
Expected output: She said, "PHP is straightforward once you practise."
The backslash \" tells PHP to treat the double quote as a literal character rather than the end of the string.
If you see Parse error here: You most likely have an unescaped quote inside a double-quoted string. Either escape the inner quotes with \" or switch the outer quotes to single quotes: 'She said, "PHP is fine."'.
2. Working with Operators
Step 3: Arithmetic and comparison operators.
<?php
$a = 15;
$b = 4;
echo $a % $b; // Modulus: remainder after division
echo "\n";
echo ($a === $b) ? "Equal" : "Not equal";
?>
Expected output:
3
Not equal
The === operator checks both value and type. This prevents a classic PHP pitfall: 0 == "a" evaluates to true in older PHP versions because of loose type juggling. Use === by default unless you specifically need loose comparison.
3. HTML Form Processing
Step 4: Retrieve and display form input safely.
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = htmlspecialchars($_POST["name"]);
echo "Hello, " . $name . "!";
}
?>
<form method="POST">
<input type="text" name="name">
<button type="submit">Submit</button>
</form>
htmlspecialchars() converts characters like < and > into their HTML entity equivalents.
If you omit it: A user entering <script>alert('XSS')</script> into the name field would have that script execute in the browser. That is a cross-site scripting (XSS) vulnerability – one of the most common security flaws in PHP applications.
Before (unsafe):
echo "Hello, " . $_POST["name"] . "!";
After (safe):
echo "Hello, " . htmlspecialchars($_POST["name"]) . "!";
Always sanitise user input before echoing it to the page.
If you see a blank page after submitting the form: Check that the form’s method attribute is POST and that you are checking $_SERVER["REQUEST_METHOD"] == "POST". If you used GET in the form but POST in the PHP check, the condition will never be true.
4. Real Web Tasks
These exercises move you from toy scripts to genuinely useful code.
Step 5: Detect the client’s browser.
<?php
$user_agent = $_SERVER['HTTP_USER_AGENT'];
if (strpos($user_agent, 'Firefox') !== false) {
echo "You are using Firefox.";
} elseif (strpos($user_agent, 'Chrome') !== false) {
echo "You are using Chrome.";
} else {
echo "Unknown browser.";
}
?>
The $_SERVER['HTTP_USER_AGENT'] superglobal contains the browser string sent with every HTTP request. Note that user agents can be spoofed – this is useful for analytics and adaptive layouts, not for security decisions.
Step 6: Retrieve the client IP address.
<?php
$ip = $_SERVER['REMOTE_ADDR'];
echo "Your IP address is: " . $ip;
?>
If you see 127.0.0.1 here: That is expected during local testing. It means your browser and server are on the same machine. On a live server, this will return the visitor’s actual IP address.
Step 7: Parse a URL into components.
<?php
$url = "https://example.co.uk/page?ref=newsletter&id=42";
$parts = parse_url($url);
echo $parts['host']; // example.co.uk
echo "\n";
echo $parts['query']; // ref=newsletter&id=42
?>
parse_url() breaks a URL into its constituent parts: scheme, host, path, query string, and fragment. This is invaluable when building redirect logic or processing external links.
If $parts['query'] is empty: Check that the URL contains a ? before the query string. parse_url() will not return a query key if no query string is present, and accessing a missing array key produces a PHP notice.
Step 8: Perform a page redirect.
<?php
header("Location: https://drs-web.co.uk");
exit();
?>
Always call exit() immediately after header("Location: ...").
Common mistake – before (incorrect):
header("Location: https://example.co.uk");
// Code continues running here - this is a bug
doSomethingDangerous();
After (correct):
header("Location: https://example.co.uk");
exit();
Without exit(), PHP continues executing the rest of the script even though the browser has been redirected. This can expose logic that should never run and cause unpredictable side effects.
If you see Cannot modify header information - headers already sent: This means PHP has already started sending output (usually because of a blank line or whitespace before your opening <?php tag, or an echo earlier in the file). Headers must be sent before any output.
5. Email Validation
Step 9: Validate an email address with a built-in filter.
<?php
$email = "user@example.co.uk";
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Valid email format.";
} else {
echo "Invalid email format.";
}
?>
FILTER_VALIDATE_EMAIL is PHP’s built-in validation tool and handles the vast majority of real-world email addresses correctly. It does not guarantee full RFC 5321 compliance – for edge cases in high-volume transactional email systems, a dedicated library may be more appropriate – but for standard web forms, this filter is exactly the right tool.
Working Through Exercises Effectively
Exercises work best when you attempt the problem first, get it wrong, then compare with the solution. The error message you encounter is not a failure – it is the most useful information you will receive.
PHP’s error messages are descriptive once you know how to read them:
Parse error: syntax error, unexpected token– check the line cited and the line above it for an unclosed bracket, missing semicolon, or mismatched quote.Undefined variable– you referenced a variable before assigning it, or misspelled its name.Call to undefined function– you called a function that does not exist, possibly because of a typo or because you are on a PHP version where that function is not available.
The PHP community is large and active – when you get stuck on an exercise, the answer almost certainly exists in a forum thread written by someone who encountered exactly the same confusion.
How to Use Exercises Alongside Framework Learning
Once you are comfortable with PHP basics, the next natural step is working with a framework that removes boilerplate and enforces structure. If you are evaluating modern PHP frameworks, the Laravel 13 upgrade guide is worth reading – but get the fundamentals right first. Frameworks make considerably more sense when you understand what they are abstracting away.
Next Steps
After working through PHP basic exercises, move on to:
- Object-oriented PHP – classes, inheritance, and interfaces
- Date and time handling –
strtotime()is more powerful than most tutorials show; it accepts relative expressions likestrtotime('+2 weeks')andstrtotime('last Monday') - Database interaction – PDO or MySQLi for querying databases safely
- Sessions and cookies – managing state across page requests
- Composer – package management and dependency handling
- A PHP framework – Laravel or Slim for structured application development
The exercises you complete today are the foundation everything else builds on. Keep a log of the problems that tripped you up – they become your personal study guide.
If you are building a PHP-based project and need professional development support, the team at drs-web.co.uk/contact can help – whether that is reviewing your codebase, optimising your architecture, or building something new from scratch.
Frequently Asked Questions
Q: What are PHP basic exercises good for if I already know another programming language?
A: Even experienced developers use PHP basic exercises to learn PHP-specific syntax and behaviour, particularly type juggling, superglobals like $_SERVER and $_POST, and PHP’s approach to string handling, which differs meaningfully from Python or JavaScript.
Q: Do I need a local server to practise PHP exercises?
A: Not necessarily. Resources like w3resource provide an in-browser code editor on each exercise page, allowing you to write and run PHP without installing anything locally. For more serious practice, a local environment like XAMPP or Laragon is recommended – setup takes under five minutes.
Q: Is FILTER_VALIDATE_EMAIL reliable for validating email addresses in PHP?
A: It is reliable for standard web form validation and handles the majority of real-world email formats correctly. However, it does not guarantee full RFC 5321 compliance, so for high-volume transactional email systems a dedicated validation library may be more appropriate.
Q: How many PHP exercises should I complete before moving to a framework like Laravel?
A: There is no fixed number, but aim to be comfortable with variables, operators, form handling, and basic string and date functions before tackling a framework. Understanding what the framework abstracts makes learning it considerably faster.
Q: What is the most common mistake beginners make in PHP exercises?
A: Forgetting the $ prefix on variable names causes parse errors that confuse beginners expecting a different kind of error message. A close second is omitting exit() after a header() redirect, which allows the rest of the script to execute unexpectedly.
Source: https://www.w3resource.com/php-exercises/php-basic-exercises.php
This article was researched and written with AI assistance, then reviewed for accuracy and quality. Kev Parker uses AI tools to help produce content faster while maintaining editorial standards.
Need help with your web project?
From one-day launches to full-scale builds, DRS Web Development delivers modern, fast websites.
