TExcelTAD
Home › PHP › PHP Exercises

PHP Exercises

Time to practise! Every exercise has a starter playground that already runs and prints a placeholder result, so you can see the expected format. Replace the TODO parts, press ▶ Run, and compare your output with the "Expected" line. Try for a few minutes before you open the solution.

# Exercise Topics
1 Price list loops, printf, number_format
2 Initials strings, explode, array_map
3 FizzBuzz match, modulo
4 Word frequency associative arrays, sorting
5 Palindromes string functions, preg_replace
6 Grade report functions, array_filter, array_sum
7 Shopping cart class classes, exceptions
8 Shipping zones enums, match
9 Top customers PDO, SQLite, GROUP BY

1. Price list

Print each item with its price right-aligned to 8 characters and 2 decimals, then a total line.

Expected:

text
Notebook      4.50
Pen           1.20
Backpack     39.90
Total        45.60
php · try it yourself
<?php
$items = ['Notebook' => 4.5, 'Pen' => 1.2, 'Backpack' => 39.9];

// TODO: print every item formatted, then the total
foreach ($items as $name => $price) {
    echo $name, ' ', $price, "\n";
}
Notebook 4.5
Pen 1.2
Backpack 39.9
Show solution
php
<?php
$items = ['Notebook' => 4.5, 'Pen' => 1.2, 'Backpack' => 39.9];

foreach ($items as $name => $price) {
    printf("%-10s%8.2f\n", $name, $price);
}
printf("%-10s%8.2f\n", 'Total', array_sum($items));

2. Initials

Write initials(string $name): string that returns the upper-case first letter of every word, separated by dots.

Expected: initials('ada king lovelace') returns A.K.L.

php · try it yourself
<?php
function initials(string $name): string {
    // TODO: split into words, take the first letter of each, upper-case, join with dots
    return '?';
}

echo initials('ada king lovelace'), "\n";
echo initials('grace hopper'), "\n";
?
?
Show solution
php
<?php
function initials(string $name): string {
    $words = preg_split('/\s+/', trim($name));
    $letters = array_map(fn($w) => strtoupper($w[0]) . '.', $words);
    return implode('', $letters);
}

echo initials('ada king lovelace'), "\n";   // A.K.L.
echo initials('grace hopper'), "\n";        // G.H.

3. FizzBuzz

For the numbers 1 to 15 print Fizz for multiples of 3, Buzz for multiples of 5, FizzBuzz for multiples of both and the number otherwise — all on one line separated by spaces. Use match (true).

Expected: 1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz

php · try it yourself
<?php
$out = [];
for ($i = 1; $i <= 15; $i++) {
    $out[] = $i; // TODO: use match (true) to pick the word
}
echo implode(' ', $out), "\n";
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Show solution
php
<?php
$out = [];
for ($i = 1; $i <= 15; $i++) {
    $out[] = match (true) {
        $i % 15 === 0 => 'FizzBuzz',
        $i % 3 === 0  => 'Fizz',
        $i % 5 === 0  => 'Buzz',
        default       => $i,
    };
}
echo implode(' ', $out), "\n";

4. Word frequency

Count how often each word appears in the text (ignore case and punctuation) and print the three most common words with their counts, most frequent first. Ties keep their first-seen order.

Expected:

text
the: 4
cat: 3
sat: 2
php · try it yourself
<?php
$text = 'The cat sat. The dog sat too! Then the cat ran, and the CAT slept.';

$counts = [];
// TODO: lower-case, extract words, count them, sort, print the top three
print_r($counts);
Array
(
)
Show solution
php
<?php
$text = 'The cat sat. The dog sat too! Then the cat ran, and the CAT slept.';

preg_match_all('/[a-z]+/', strtolower($text), $m);
$counts = array_count_values($m[0]);
arsort($counts);   // stable since PHP 8.0, so ties keep their order

foreach (array_slice($counts, 0, 3, true) as $word => $n) {
    echo "$word: $n\n";
}

5. Palindromes

Write isPalindrome(string $s): bool that ignores case, spaces and punctuation.

Expected: racecar yes, Step on no pets! yes, PHP rocks no.

php · try it yourself
<?php
function isPalindrome(string $s): bool {
    // TODO: clean the string, then compare it with its reverse
    return false;
}

foreach (['racecar', 'Step on no pets!', 'PHP rocks'] as $s) {
    echo str_pad($s, 18), isPalindrome($s) ? 'yes' : 'no', "\n";
}
racecar           no
Step on no pets!  no
PHP rocks         no
Show solution
php
<?php
function isPalindrome(string $s): bool {
    $clean = preg_replace('/[^a-z0-9]/', '', strtolower($s));
    return $clean === strrev($clean);
}

6. Grade report

Given the scores, print the average (1 decimal), the names of everyone who passed (score ≥ 50) and the best student.

Expected:

text
Average: 59.4
Passed: Ana, Bo, Dee
Best: Dee (91)
php · try it yourself
<?php
$scores = ['Ana' => 72, 'Bo' => 55, 'Cy' => 38, 'Dee' => 91, 'Eli' => 41];

// TODO: compute and print the three lines
echo "Average: ?\n";
echo "Passed: ?\n";
echo "Best: ?\n";
Average: ?
Passed: ?
Best: ?
Show solution
php
<?php
$scores = ['Ana' => 72, 'Bo' => 55, 'Cy' => 38, 'Dee' => 91, 'Eli' => 41];

$avg = array_sum($scores) / count($scores);
$passed = array_keys(array_filter($scores, fn($s) => $s >= 50));
$best = array_search(max($scores), $scores);

printf("Average: %.1f\n", $avg);
echo 'Passed: ', implode(', ', $passed), "\n";
echo "Best: $best ({$scores[$best]})\n";

7. Shopping cart class

Complete the Cart class: add() stores a product with a quantity (throw an InvalidArgumentException with the message Quantity must be positive when the quantity is below 1) and total() returns the sum of price × quantity.

Expected:

text
Error: Quantity must be positive
Total: 23.50
php · try it yourself
<?php
class Cart {
    private array $lines = [];

    public function add(string $name, float $price, int $qty = 1): void {
        // TODO: validate $qty and store the line
    }

    public function total(): float {
        return 0; // TODO
    }
}

$cart = new Cart();
$cart->add('Mug', 8.0, 2);
$cart->add('Tea', 7.5);
try {
    $cart->add('Spoon', 1.0, 0);
} catch (InvalidArgumentException $e) {
    echo 'Error: ', $e->getMessage(), "\n";
}
printf("Total: %.2f\n", $cart->total());
Total: 0.00
Show solution
php
<?php
class Cart {
    private array $lines = [];

    public function add(string $name, float $price, int $qty = 1): void {
        if ($qty < 1) {
            throw new InvalidArgumentException('Quantity must be positive');
        }
        $this->lines[] = ['name' => $name, 'price' => $price, 'qty' => $qty];
    }

    public function total(): float {
        return array_sum(array_map(fn($l) => $l['price'] * $l['qty'], $this->lines));
    }
}

8. Shipping zones

Create a backed enum Zone with cases Local = 'L', Europe = 'EU' and World = 'W', and a method cost(float $kg): float that returns 3.00 + 1.00/kg for Local, 6.00 + 2.50/kg for Europe and 12.00 + 4.00/kg for World. Read the codes with Zone::tryFrom() and report unknown codes.

Expected:

text
L: 5.00
EU: 11.00
XX: unknown zone
W: 20.00
php · try it yourself
<?php
// TODO: declare enum Zone with a cost() method

$parcels = [['L', 2.0], ['EU', 2.0], ['XX', 1.0], ['W', 2.0]];
foreach ($parcels as [$code, $kg]) {
    echo "$code: ?\n";
}
L: ?
EU: ?
XX: ?
W: ?
Show solution
php
<?php
enum Zone: string {
    case Local = 'L';
    case Europe = 'EU';
    case World = 'W';

    public function cost(float $kg): float {
        return match ($this) {
            Zone::Local  => 3.00 + 1.00 * $kg,
            Zone::Europe => 6.00 + 2.50 * $kg,
            Zone::World  => 12.00 + 4.00 * $kg,
        };
    }
}

$parcels = [['L', 2.0], ['EU', 2.0], ['XX', 1.0], ['W', 2.0]];
foreach ($parcels as [$code, $kg]) {
    $zone = Zone::tryFrom($code);
    echo "$code: ", $zone ? number_format($zone->cost($kg), 2) : 'unknown zone', "\n";
}

9. Top customers

Using the in-memory database below, print each customer's total spending, highest first, but only customers who spent more than 50. Use one SQL query with GROUP BY and HAVING, and pass the limit 50 through a placeholder.

Expected:

text
Mila: 120
Theo: 75
php · try it yourself
<?php
$pdo = new PDO('sqlite::memory:');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec('CREATE TABLE orders (customer TEXT, amount INTEGER)');
$pdo->exec("INSERT INTO orders VALUES
    ('Mila', 40), ('Theo', 75), ('Mila', 80), ('Jun', 30), ('Jun', 15)");

// TODO: replace this query with a grouped, filtered and sorted one
$stmt = $pdo->query('SELECT customer, amount FROM orders');
foreach ($stmt->fetchAll(PDO::FETCH_KEY_PAIR) as $name => $total) {
    echo "$name: $total\n";
}
Mila: 80
Theo: 75
Jun: 15
Show solution
php
<?php
// ... same setup as above ...
$stmt = $pdo->prepare('SELECT customer, SUM(amount) AS total
                       FROM orders
                       GROUP BY customer
                       HAVING total > ?
                       ORDER BY total DESC');
$stmt->execute([50]);
foreach ($stmt->fetchAll(PDO::FETCH_KEY_PAIR) as $name => $total) {
    echo "$name: $total\n";
}

Tip: Notice how the starter for exercise 9 printed only one line per customer: FETCH_KEY_PAIR uses the first column as the array key, so later rows with the same key overwrite earlier ones.

Test yourself

Which function counts how many times each value appears in an array?

  1. count()
  2. array_count_values()
  3. array_sum()
  4. substr_count()

What does Zone::tryFrom('XX') return when no case has the value 'XX'?

  1. It throws a ValueError
  2. false
  3. null
  4. The first case

Which SQL clause filters groups after GROUP BY?

  1. WHERE
  2. HAVING
  3. FILTER
  4. LIMIT