PHP Examples and Exercises

These PHP examples and exercises help you practise what you learned in this tutorial. Try each one yourself first, then compare with the solution. Small daily practice is the fastest way to get comfortable with PHP.

Exercise 1: FizzBuzz

Print numbers 1 to 15, but print Fizz for multiples of 3, Buzz for multiples of 5 and FizzBuzz for both.

<?php
for ($i = 1; $i <= 15; $i++) {
    echo match (true) {
        $i % 15 === 0 => 'FizzBuzz',
        $i % 3 === 0 => 'Fizz',
        $i % 5 === 0 => 'Buzz',
        default => $i,
    }, ' ';
}
1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz 

Exercise 2: Word Frequency

Count how often each word appears in a sentence and show the top three.

<?php
$text = "the cat and the dog and the bird";
$counts = array_count_values(str_word_count(strtolower($text), 1));
arsort($counts);
foreach (array_slice($counts, 0, 3, true) as $word => $n) {
    echo "$word: $n\n";
}
the: 3
and: 2
cat: 1

Exercise 3: Shopping Cart Total

Given a cart array, calculate the subtotal, apply a 10% discount above 100 and format the result.

<?php
$cart = [
    ['item' => 'Shoes', 'price' => 60, 'qty' => 1],
    ['item' => 'Socks', 'price' => 5, 'qty' => 4],
    ['item' => 'Cap', 'price' => 25, 'qty' => 1],
];
$subtotal = array_sum(array_map(fn($l) => $l['price'] * $l['qty'], $cart));
$discount = $subtotal > 100 ? $subtotal * 0.10 : 0;
printf("Subtotal: %.2f\nDiscount: %.2f\nTotal: %.2f", $subtotal, $discount, $subtotal - $discount);
Subtotal: 105.00
Discount: 10.50
Total: 94.50

Exercise 4: Bank Account Class

Build a class with deposit and withdraw methods that refuses to go below zero.

<?php
class BankAccount {
    private float $balance = 0;

    public function deposit(float $amount): static {
        if ($amount <= 0) throw new ValueError('Amount must be positive');
        $this->balance += $amount;
        return $this;
    }
    public function withdraw(float $amount): static {
        if ($amount > $this->balance) throw new RuntimeException('Insufficient funds');
        $this->balance -= $amount;
        return $this;
    }
    public function balance(): float { return $this->balance; }
}

$acc = (new BankAccount())->deposit(200)->withdraw(50);
echo $acc->balance(), "\n";
try { $acc->withdraw(500); } catch (RuntimeException $e) { echo $e->getMessage(); }
150
Insufficient funds

More Ideas to Practise

  • A contact form that validates input and saves messages to a CSV file
  • A to-do list stored in the session with add and delete buttons
  • A tiny JSON API that returns products from a MySQL table using PDO
  • A password strength checker using regular expressions
  • Rebuild one of these in Laravel after finishing the Laravel tutorial

Frequently asked questions

What are good PHP projects for beginners?

A contact form, a to-do app, a simple blog with MySQL, a URL shortener or a small JSON API are all great first projects.

How can I practise PHP online?

Install PHP locally and run scripts with php file.php, or use online sandboxes such as 3v4l.org to test snippets across PHP versions.

What should I learn after PHP basics?

Learn Composer, SQL, and a framework. Laravel is the most popular choice and is covered in the Laravel tutorial on this site.