Skip to content
Tutorials Center
My learning

Topics

Lesson 146 of 147 ยท Practice and Review

PHP Practice Exercises

30 graded PHP exercises with solutions on loops, functions, strings, regex, arrays, sorting, classes, enums, exceptions, JSON, CSV, forms and PDO. Run PHP online.

You learn PHP by writing PHP. Lessons build understanding, but only practice builds the reflexes: picking the right array function without looking it up, remembering that strlen counts bytes, comparing with ===, escaping output, binding values in SQL instead of gluing strings together. This page collects 30 exercises that cover the whole course, grouped by topic and ordered from beginner to advanced inside each group.

Every exercise has a short task, an editor with starter code, and a hidden solution. The starter code runs as given: the functions you need to write are stubs that return a placeholder value, and the comments show the output you should get once your code works. Replace the stub body, press Run, and compare.

  • Try first, peek later. Give each exercise a real attempt before you open the solution. A few minutes of being stuck is where the learning happens.
  • Compare, don't copy. Your solution can look different from ours and still be right. Read ours for ideas, then improve yours.
  • Read the diagnostics. Our PHP runs with every error level reported, so warnings such as "Undefined array key" or "Undefined variable" appear in the output. Treat each one as a bug to fix.
  • Test the edges. Empty strings, empty arrays, zero, negative numbers and non-English text are where PHP programs break. Most exercises include at least one edge case in their test calls.

Each group links to the lessons it practices. Keep the cheat sheet open in another tab, and look at the 50 classic programs if you want worked examples first.

Basics and control flow

These practice output, if statements, switch and match and loops.

1. Times table (Beginner)

Read one whole number from the Input box and print its times table from 1 to 10 in the format shown in the comment. Use printf with field widths so the columns line up.

PHP Exercise 1: Times table

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Show solution
PHP
for ($i = 1; $i <= 10; $i++) {
    printf("%d x %2d = %2d\n", $n, $i, $n * $i);
}

%2d pads each number to two characters with spaces, so the = signs and the results line up in columns. For numbers whose products reach three digits, widen the second field to %3d.

2. Shipping cost (Beginner)

Write shippingCost(string $zone, float $weightKg) with a match expression: zone 'domestic' costs 5.00, 'europe' 12.50 and 'world' 25.00, plus 2.00 for every started kilogram above 1 kg (use ceil). An unknown zone should throw an InvalidArgumentException.

PHP Exercise 2: Shipping cost

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Show solution
PHP
function shippingCost(string $zone, float $weightKg): float
{
    $base = match ($zone) {
        'domestic' => 5.00,
        'europe' => 12.50,
        'world' => 25.00,
        default => throw new InvalidArgumentException("Unknown zone: $zone"),
    };
    $extraKg = max(0, ceil($weightKg) - 1);
    return $base + 2.00 * $extraKg;
}

throw is an expression since PHP 8.0, so it can sit directly in the default arm. ceil(2.2) is 3, so a 2.2 kg parcel pays for two extra kilograms; max(0, ...) keeps light parcels from getting a negative surcharge.

3. Letter grades (Beginner)

Write letterGrade(int $score) that returns 'A' for 90โ€“100, 'B' for 80โ€“89, 'C' for 70โ€“79, 'D' for 60โ€“69 and 'F' below 60. Scores outside 0โ€“100 return '?'. The program reads the scores from the Input box.

PHP Exercise 3: Letter grades

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Show solution
PHP
function letterGrade(int $score): string
{
    return match (true) {
        $score < 0, $score > 100 => '?',
        $score >= 90 => 'A',
        $score >= 80 => 'B',
        $score >= 70 => 'C',
        $score >= 60 => 'D',
        default => 'F',
    };
}

match (true) returns the first arm whose condition is true, so the order of the arms matters. An arm can list several conditions separated by commas.

4. Digital root (Intermediate)

The digital root of a non-negative number is what you get by adding its digits again and again until one digit is left: 9875 โ†’ 29 โ†’ 11 โ†’ 2. Write digitalRoot(int $n) with loops (no strings). Bonus: there's a one-line formula.

PHP Exercise 4: Digital root

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Show solution
PHP
function digitalRoot(int $n): int
{
    while ($n >= 10) {
        $sum = 0;
        while ($n > 0) {
            $sum += $n % 10;
            $n = intdiv($n, 10);
        }
        $n = $sum;
    }
    return $n;
}

The inner loop adds the digits once; the outer loop repeats until a single digit remains. The formula version is $n === 0 ? 0 : 1 + ($n - 1) % 9, because a number and its digit sum leave the same remainder when divided by 9.

Functions

These practice functions, parameters and arguments, recursion, variable scope and closures.

5. Average of any number of values (Beginner)

Write average(float ...$numbers) that returns the average of its arguments, or null when it gets none. Then call it with an array unpacked into arguments.

PHP Exercise 5: Variadic average

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Show solution
PHP
function average(float ...$numbers): ?float
{
    if ($numbers === []) {
        return null;
    }
    return array_sum($numbers) / count($numbers);
}

Inside the function, $numbers is an ordinary array. Integers are accepted for float parameters even in strict mode, and ...$scores at the call site spreads an array into separate arguments.

6. Flatten a nested array (Intermediate)

Write a recursive flatten(array $items) that returns all the values of a nested array as one flat list, in order. is_array tells you when to recurse.

PHP Exercise 6: Flatten

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Show solution
PHP
function flatten(array $items): array
{
    $result = [];
    foreach ($items as $item) {
        if (is_array($item)) {
            array_push($result, ...flatten($item));
        } else {
            $result[] = $item;
        }
    }
    return $result;
}

Each nested array is flattened by the same function, and its values are appended with the spread operator. Empty inner arrays simply contribute nothing. A non-recursive alternative uses array_walk_recursive with a closure that collects values by reference.

7. Count calls with a static variable (Intermediate)

Write nextTicket() that returns 'T-001' the first time it's called, 'T-002' the next time, and so on. Don't use a global variable: use a static variable inside the function.

PHP Exercise 7: Ticket numbers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Show solution
PHP
function nextTicket(): string
{
    static $counter = 0;
    $counter++;
    return sprintf('T-%03d', $counter);
}

A static local variable is initialized once and keeps its value between calls, but stays invisible outside the function. %03d pads with zeros to three digits.

8. Memoize any function (Advanced)

Write memoize(callable $function) that returns a closure which caches results by argument list, so a slow function only runs once per distinct input. The test counts how often the real function runs.

PHP Exercise 8: Memoize

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Show solution
PHP
function memoize(callable $function): Closure
{
    $cache = [];
    return function (mixed ...$args) use ($function, &$cache): mixed {
        $key = serialize($args);
        if (!array_key_exists($key, $cache)) {
            $cache[$key] = $function(...$args);
        }
        return $cache[$key];
    };
}

The cache must be captured by reference (&$cache); captured by value, each call would see the original empty array. serialize turns the argument list into a string key, and array_key_exists (unlike isset) also works when a cached result is null. Arrow functions can't be used here because they capture by value only.

Strings

These practice string functions, multibyte strings, formatting and regular expressions.

9. Initials (Beginner)

Write initials(string $fullName) that returns the uppercase first letter of each word, so 'ada lovelace' becomes 'AL'. It must work for names like 'ร‰mile Zola', and extra spaces must not create empty initials.

PHP Exercise 9: Initials

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Show solution
PHP
function initials(string $fullName): string
{
    $words = preg_split('/\s+/', trim($fullName), flags: PREG_SPLIT_NO_EMPTY);
    $letters = array_map(fn (string $word): string => mb_substr($word, 0, 1), $words);
    return mb_strtoupper(implode('', $letters));
}

$word[0] would take only the first byte of รฉ, which is half a character, so the solution uses mb_substr. PREG_SPLIT_NO_EMPTY drops the empty pieces that repeated spaces would create.

10. Mask an email address (Beginner)

Write maskEmail(string $email) that keeps the first character of the local part, replaces the rest of it with * (same length), and keeps the domain: '[email protected]' becomes 'm****@example.com'. Use strrpos to find the last @.

PHP Exercise 10: Mask an email

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Show solution
PHP
function maskEmail(string $email): string
{
    $at = strrpos($email, '@');
    if ($at === false || $at === 0) {
        return $email;
    }
    return $email[0] . str_repeat('*', $at - 1) . substr($email, $at);
}

strrpos returns the position of the last @ or false, so compare with === false: a position of 0 is falsy too. substr($email, $at) keeps everything from the @ onward.

11. Caesar cipher (Intermediate)

Write caesar(string $text, int $shift) that shifts every ASCII letter by $shift places, wrapping around the alphabet and keeping case. Other characters stay unchanged. A negative shift decodes.

PHP Exercise 11: Caesar cipher

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Show solution
PHP
function caesar(string $text, int $shift): string
{
    $shift = (($shift % 26) + 26) % 26;
    $result = '';
    foreach (str_split($text) as $char) {
        if (ctype_upper($char) || ctype_lower($char)) {
            $base = ord(ctype_upper($char) ? 'A' : 'a');
            $char = chr($base + (ord($char) - $base + $shift) % 26);
        }
        $result .= $char;
    }
    return $result;
}

$shift % 26 keeps the sign in PHP (-3 % 26 is -3), so adding 26 and taking % 26 again maps every shift into 0โ€“25. ord and chr convert between characters and their byte values. PHP's built-in str_rot13 is the special case with a shift of 13.

12. Extract hashtags (Intermediate)

Write hashtags(string $post) that returns the unique hashtags in a post, lowercased and without #, in order of first appearance. A hashtag is # followed by letters, digits or underscores, and it must not be part of a longer word (so C# or abc#def don't count).

PHP Exercise 12: Hashtags

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Show solution
PHP
function hashtags(string $post): array
{
    preg_match_all('/(?<![\w#])#(\w+)/u', $post, $matches);
    $tags = array_map(mb_strtolower(...), $matches[1]);
    return array_values(array_unique($tags));
}

The negative lookbehind (?<![\w#]) rejects a # that directly follows a word character, which rules out C# and abc#def. With the u flag, \w matches letters from every alphabet, so #Cafรฉ works. array_values renumbers the keys that array_unique leaves with gaps.

13. Truncate at a word boundary (Intermediate)

Write excerpt(string $text, int $maxChars) that returns the text unchanged if it fits, and otherwise cuts it at the last space within $maxChars characters and adds โ€ฆ. Count characters, not bytes.

PHP Exercise 13: Excerpt

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Show solution
PHP
function excerpt(string $text, int $maxChars): string
{
    if (mb_strlen($text) <= $maxChars) {
        return $text;
    }
    $cut = mb_substr($text, 0, $maxChars);
    $lastSpace = mb_strrpos($cut, ' ');
    if ($lastSpace !== false) {
        $cut = mb_substr($cut, 0, $lastSpace);
    }
    return rtrim($cut, " ,.;:") . 'โ€ฆ';
}

When there's no space at all (one long word), the function cuts in the middle of the word rather than returning nothing. rtrim removes punctuation left at the end so you don't get "custard,โ€ฆ".

14. Format an invoice table (Intermediate)

Print the invoice lines as a table with a name column 14 characters wide (left-aligned), a quantity column 4 wide, and a price and line-total column 10 wide (right-aligned, two decimals, thousands separator), followed by a total line. Use sprintf/printf and number_format.

PHP Exercise 14: Invoice table

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Show solution
PHP
printf("%-14s %4s %10s %10s\n", 'Item', 'Qty', 'Price', 'Total');
$sum = 0;
foreach ($lines as $line) {
    $total = $line['qty'] * $line['price'];
    $sum += $total;
    printf("%-14s %4d %10s %10s\n", $line['name'], $line['qty'], number_format($line['price'], 2), number_format($total, 2));
}
printf("%41s\n", number_format($sum, 2));

%-14s left-aligns in 14 characters and %10s right-aligns. The numbers are formatted to strings with number_format first, because printf's %f has no thousands separator. Real invoices store money as integer cents; floats are fine here only for display.

Arrays

These practice arrays, array functions, map, filter and reduce, sorting and multidimensional arrays.

15. Running totals (Beginner)

Write runningTotals(array $numbers) that returns an array where each element is the sum of all numbers up to and including that position.

PHP Exercise 15: Running totals

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Show solution
PHP
function runningTotals(array $numbers): array
{
    $totals = [];
    $sum = 0;
    foreach ($numbers as $number) {
        $sum += $number;
        $totals[] = $sum;
    }
    return $totals;
}

One pass with a running $sum is all you need. Recomputing array_sum(array_slice(...)) for every position would give the same result but do quadratic work.

16. Filter and map products (Beginner)

From the product list, produce the names of products that are in stock and cost less than 50, sorted alphabetically. Use array_filter, array_map (or array_column) and sort, not a foreach loop.

PHP Exercise 16: Cheap products in stock

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Show solution
PHP
$available = array_filter($products, fn (array $p): bool => $p['stock'] > 0 && $p['price'] < 50);
$names = array_column($available, 'name');
sort($names);

array_filter keeps the original keys, which doesn't matter here because array_column builds a new list. sort sorts in place and returns true, so it can't be chained.

17. Sort by several keys (Intermediate)

Sort the users by age descending, and users with the same age by name ascending. Use one usort call and the spaceship operator <=>.

PHP Exercise 17: Multi-key sort

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Show solution
PHP
usort($users, fn (array $a, array $b): int => [$b['age'], $a['name']] <=> [$a['age'], $b['name']]);

Comparing two arrays with <=> compares element by element, so the first key decides unless it's equal. Swapping $a and $b for the age makes that key descending while the name stays ascending.

18. Invert a map with duplicate values (Intermediate)

array_flip loses data when several keys share a value. Write invert(array $map) that groups the keys by value instead: ['ana' => 'admin', 'bo' => 'editor', 'cy' => 'admin'] becomes ['admin' => ['ana', 'cy'], 'editor' => ['bo']].

PHP Exercise 18: Invert a map

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Show solution
PHP
function invert(array $map): array
{
    $inverted = [];
    foreach ($map as $key => $value) {
        $inverted[$value][] = $key;
    }
    return $inverted;
}

$inverted[$value][] = $key creates the inner array the first time a value appears and appends to it afterward. array_flip keeps only the last key for each value, which is why ana disappears from its output.

19. Search with array_find, array_any and array_all (Intermediate)

Using the PHP 8.4 functions array_find, array_any and array_all (no loops), find the first overdue unfinished task, check whether any task is high priority, and check whether all tasks have an owner.

PHP Exercise 19: array_find and friends

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Show solution
PHP
$firstOverdue = array_find($tasks, fn (array $t): bool => !$t['done'] && $t['due'] < $today);
$anyHigh = array_any($tasks, fn (array $t): bool => $t['priority'] === 'high');
$allOwned = array_all($tasks, fn (array $t): bool => $t['owner'] !== '');

array_find returns the first matching element (or null), and array_any/array_all stop as soon as the answer is known. Dates in YYYY-MM-DD format compare correctly as strings, because the most significant part comes first. "Pay invoice" is overdue too, but it's done.

20. Read nested values with dot notation (Advanced)

Write dataGet(array $data, string $path, mixed $default = null) that follows a dotted path such as 'user.address.city' through nested arrays, and returns $default when any step is missing. Numeric segments work as list indexes ('orders.1.total').

PHP Exercise 20: Dot notation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Show solution
PHP
function dataGet(array $data, string $path, mixed $default = null): mixed
{
    $current = $data;
    foreach (explode('.', $path) as $segment) {
        if (!is_array($current) || !array_key_exists($segment, $current)) {
            return $default;
        }
        $current = $current[$segment];
    }
    return $current;
}

array_key_exists (not isset) is the right test, because zip exists with the value null and should be returned as null, not replaced by the default. The string segment '1' finds the integer key 1, since PHP casts numeric string keys to integers. The is_array check stops the walk when a path continues past a plain value, like 'Ana'.

Object-oriented PHP

These practice classes and objects, constructors, readonly properties, enums, interfaces and iterators.

21. An immutable Money class (Intermediate)

Complete the readonly Money class: add() returns a new object (the currency must match, otherwise throw InvalidArgumentException), and format() returns a string like 'EUR 12.50'. Amounts are stored in cents.

PHP Exercise 21: Money value object

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Show solution
PHP
public function add(Money $other): Money
{
    if ($other->currency !== $this->currency) {
        throw new InvalidArgumentException("Cannot add {$other->currency} to {$this->currency}");
    }
    return new Money($this->cents + $other->cents, $this->currency);
}

public function format(): string
{
    return sprintf('%s %s', $this->currency, number_format($this->cents / 100, 2));
}

A readonly class can't change its properties after construction, so every operation returns a new object and $price still holds 12.50 afterward. Integer cents keep the addition exact.

22. An enum with behavior (Intermediate)

Complete the OrderStatus backed enum: label() returns a human-friendly name, and canMoveTo() allows only these transitions: Pending โ†’ Paid or Cancelled, Paid โ†’ Shipped or Cancelled, Shipped โ†’ Delivered. Then parse a status from a string with tryFrom.

PHP Exercise 22: Enum with methods

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Show solution
PHP
public function label(): string
{
    return match ($this) {
        self::Pending => 'Waiting for payment',
        self::Paid => 'Payment received',
        self::Shipped => 'On its way',
        self::Delivered => 'Delivered',
        self::Cancelled => 'Cancelled',
    };
}

public function canMoveTo(OrderStatus $next): bool
{
    $allowed = match ($this) {
        self::Pending => [self::Paid, self::Cancelled],
        self::Paid => [self::Shipped, self::Cancelled],
        self::Shipped => [self::Delivered],
        self::Delivered, self::Cancelled => [],
    };
    return in_array($next, $allowed, true);
}

A match on $this without a default arm is exhaustive: if someone adds a new case and forgets to update the method, PHP throws an UnhandledMatchError instead of silently doing the wrong thing. tryFrom returns null for unknown values, and the nullsafe operator ?-> turns the whole call into null.

23. Interchangeable discount rules (Intermediate)

Complete two classes implementing the Discount interface: PercentOff (e.g. 10 percent off) and FixedOff (a fixed amount in cents, never below zero). The checkout function applies a list of discounts in order without knowing their classes.

PHP Exercise 23: Discount strategies

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Show solution
PHP
public function apply(int $cents): int // PercentOff
{
    return (int) round($cents * (100 - $this->percent) / 100);
}

public function apply(int $cents): int // FixedOff
{
    return max(0, $cents - $this->amountCents);
}

This is the strategy pattern: checkout depends only on the Discount interface, so you can add new rules (buy-one-get-one, coupons) without touching it. round returns a float, so the result is cast back to int; 999 ร— 0.85 = 849.15 rounds to 849.

24. A typed stack that works with count() and foreach (Advanced)

Complete Stack: push, pop (throws UnderflowException when empty), peek (returns null when empty), plus Countable and IteratorAggregate so count($stack) and foreach work. Iteration goes from the top of the stack down.

PHP Exercise 24: Stack class

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Show solution
PHP
public function push(string $item): void
{
    $this->items[] = $item;
}

public function pop(): string
{
    if ($this->items === []) {
        throw new UnderflowException('The stack is empty.');
    }
    return array_pop($this->items);
}

public function peek(): ?string
{
    return array_last($this->items);
}

public function count(): int
{
    return count($this->items);
}

public function getIterator(): Iterator
{
    return new ArrayIterator(array_reverse($this->items));
}

array_last (PHP 8.5) returns the last element or null for an empty array; in older versions use $this->items[array_key_last($this->items)] ?? null or end(). Implementing Countable and IteratorAggregate makes the object feel like a built-in collection, while the array stays private.

Errors and exceptions

These practice exceptions and custom exceptions.

25. Parse input with exceptions (Intermediate)

Write parseAge(string $input) that trims the input and returns it as an int. Throw InvalidArgumentException with the messages shown when the input isn't a whole number or is outside 0โ€“150. Use filter_var with FILTER_VALIDATE_INT and its options.

PHP Exercise 25: Parse an age

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Show solution
PHP
function parseAge(string $input): int
{
    $value = filter_var(trim($input), FILTER_VALIDATE_INT);
    if ($value === false) {
        throw new InvalidArgumentException('Age must be a whole number.');
    }
    $age = filter_var($value, FILTER_VALIDATE_INT, ['options' => ['min_range' => 0, 'max_range' => 150]]);
    if ($age === false) {
        throw new InvalidArgumentException('Age must be between 0 and 150.');
    }
    return $age;
}

Two checks give two clear messages. Unlike an (int) cast, which turns '12.5' into 12 and 'abc' into 0, filter_var rejects anything that isn't exactly an integer (it does allow surrounding whitespace, but trimming first makes the intent clear). The test loop calls parseAge before it echoes anything, so a failed parse never leaves half a line behind.

26. Retry with exception chaining (Advanced)

Write retry(int $attempts, callable $operation) that calls $operation until it succeeds or the attempts run out. Print a line for each failure. When every attempt fails, throw a RuntimeException that wraps the last exception as its previous.

PHP Exercise 26: Retry helper

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Show solution
PHP
function retry(int $attempts, callable $operation): mixed
{
    $lastError = null;
    for ($attempt = 1; $attempt <= $attempts; $attempt++) {
        try {
            return $operation();
        } catch (Exception $e) {
            echo "attempt $attempt failed: {$e->getMessage()}\n";
            $lastError = $e;
        }
    }
    throw new RuntimeException("Gave up after $attempts attempts", previous: $lastError);
}

return inside try leaves the function as soon as an attempt works. Passing the last exception as previous keeps the original cause and its stack trace for logging. Catching Exception (not Throwable) lets real bugs such as a TypeError escape immediately instead of being retried. Real retry helpers also wait between attempts, often longer each time.

Files, JSON and CSV

These practice reading and writing files, JSON and CSV files.

27. Merge a JSON config with defaults (Intermediate)

Decode the user's JSON configuration (with JSON_THROW_ON_ERROR), merge it recursively over the defaults so nested keys the user didn't set are kept, and print the result as pretty JSON. Invalid JSON should print Invalid config: and the error message.

PHP Exercise 27: Merge JSON config

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Show solution
PHP
function loadConfig(string $json, array $defaults): array
{
    $user = json_decode($json, true, flags: JSON_THROW_ON_ERROR);
    return array_replace_recursive($defaults, $user);
}

array_replace_recursive walks both arrays and replaces only the keys present in the second one, so database.host survives. array_merge would replace the whole database array, and array_merge_recursive would turn conflicting scalars like port into arrays of both values. Without JSON_THROW_ON_ERROR, invalid JSON just returns null, which is easy to miss.

28. Totals per category from a CSV file (Intermediate)

The program writes a small CSV file to a temporary path. Read it back with fopen and fgetcsv, add up the amount column per category, and print the categories sorted by total, largest first. Delete the file at the end.

PHP Exercise 28: CSV totals

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Show solution
PHP
$handle = fopen($path, 'r');
if ($handle === false) {
    exit("Cannot open the file.\n");
}
fgetcsv($handle, escape: ''); // skip the header row
while (($row = fgetcsv($handle, escape: '')) !== false) {
    [, $category, $amount] = $row;
    $totals[$category] = ($totals[$category] ?? 0) + (float) $amount;
}
fclose($handle);
arsort($totals);

fgetcsv understands the quotes around "Books, magazines", which a plain explode(',') would split in two. ?? 0 avoids an "Undefined array key" warning the first time a category appears, and arsort sorts by value while keeping the category keys.

Web and databases

These practice handling forms, form validation, preventing XSS and prepared statements. The form exercise simulates a POST request by filling $_POST at the top of the script; on a real server, PHP fills it from the submitted form.

29. Validate a sign-up form (Intermediate)

Write validateSignup(array $input) that returns an array of error messages keyed by field name (empty when everything is valid): name is required and at most 50 characters, email must be a valid address, age must be a whole number of at least 13. Then print the errors, escaped for HTML.

PHP Exercise 29: Sign-up validation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Show solution
PHP
function validateSignup(array $input): array
{
    $errors = [];
    $name = trim((string) ($input['name'] ?? ''));
    $email = trim((string) ($input['email'] ?? ''));
    $age = filter_var($input['age'] ?? null, FILTER_VALIDATE_INT);

    if ($name === '') {
        $errors['name'] = 'Please enter your name.';
    } elseif (mb_strlen($name) > 50) {
        $errors['name'] = 'Your name can be at most 50 characters.';
    }
    if (filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
        $errors['email'] = "\"$email\" is not a valid email address.";
    }
    if ($age === false || $age === null) {
        $errors['age'] = 'Please enter your age as a whole number.';
    } elseif ($age < 13) {
        $errors['age'] = 'You must be at least 13.';
    }
    return $errors;
}

Every field is read with ?? '' (or ?? null), because a crafted request can leave any field out. The error message repeats what the user typed, so it must be escaped: htmlspecialchars turns the <b> tags into harmless text. On a web server the browser would render the escaped tags as visible characters instead of bold text.

30. Query a database safely with PDO (Advanced)

The script creates an in-memory SQLite database with customers and orders. Write topCustomers(PDO $pdo, string $country, int $limit) that returns the customers from one country with their order count and total, largest total first. Use a prepared statement with named placeholders, never string concatenation.

PHP Exercise 30: PDO top customers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Show solution
PHP
function topCustomers(PDO $pdo, string $country, int $limit): array
{
    $statement = $pdo->prepare(<<<SQL
        SELECT c.name, COUNT(o.id) AS orders, SUM(o.total_cents) AS total_cents
        FROM customers AS c
        JOIN orders AS o ON o.customer_id = c.id
        WHERE c.country = :country
        GROUP BY c.id, c.name
        ORDER BY total_cents DESC
        LIMIT :limit
        SQL);
    $statement->bindValue(':country', $country);
    $statement->bindValue(':limit', $limit, PDO::PARAM_INT);
    $statement->execute();
    return $statement->fetchAll();
}

The country is sent to the database separately from the SQL, so the attack string is just an unusual country name that matches no rows. LIMIT is bound with PDO::PARAM_INT so it's sent as a number. The same code works with MySQL by changing only the DSN. See CRUD with PDO for the full pattern.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In exercise 8, why must the closure capture the cache as &$cache?

    use ($cache) copies the value when the closure is created. Writes inside the closure then change only that call's copy. use (&$cache) shares one array across all calls.
  2. 2. What does array_flip(['ana' => 'admin', 'cy' => 'admin']) return (exercise 18)?

    Values become keys, and a key can only exist once, so each later duplicate overwrites the earlier one. Group the keys yourself when values repeat.
  3. 3. Why does exercise 20 use array_key_exists instead of isset to test each path segment?

    isset checks that the key exists AND its value isn't null. To tell a missing key from a key holding null, use array_key_exists.
  4. 4. In exercise 25, what does (int) '12.5abc' give, compared with filter_var('12.5abc', FILTER_VALIDATE_INT)?

    A cast takes the leading numeric part and silently drops the rest. FILTER_VALIDATE_INT accepts only a complete integer, which is what you want for validation.
  5. 5. In exercise 30, why is the attack string harmless?

    With prepared statements the SQL text and the values travel separately. The quote characters are just part of a country name that matches nothing.

Summary

  • The basics exercises train loops, input with fgets(STDIN), printf field widths and match, including match (true) and throw as an expression.
  • Function exercises cover variadics and spreading, recursion, static variables and closures that capture by reference.
  • String exercises revolve around bytes vs characters (mb_*), safe position checks with === false, and regular expressions with lookbehinds and the u flag.
  • Array exercises are about keys: grouping with $groups[$key][] = ..., multi-key sorting with arrays and <=>, array_find/array_any/array_all (PHP 8.4), and array_key_exists for values that may be null.
  • OOP exercises build immutable value objects, enums with exhaustive match, interchangeable strategies behind an interface, and collections with Countable and IteratorAggregate.
  • Error, file and web exercises validate input strictly with filter_var, chain exceptions with previous, read CSV with fgetcsv, merge JSON with array_replace_recursive, escape every output, and bind every SQL value.

Next: PHP Interview Questions, to practice explaining these ideas out loud.