Skip to content
Back to Interview Guides
Interview Guide

30 PHP Coding Challenges for Junior and Senior Developers

· 8 min read

PHP Challenges for the Modern Web

For decades, PHP has been the backbone of the web, powering everything from personal blogs to massive e-commerce platforms. For developers, a strong command of PHP is a ticket to a vast world of web development opportunities. For employers, finding engineers who can write clean, secure, and modern PHP is essential for building and maintaining robust web applications.

That’s why we’ve put together this collection of 30 hands-on PHP challenges. We’ve organized them into three levels—10 for Junior, 10 for Mid-Level, and 10 for Senior developers—to help you build your skills, prepare for your next interview, or find the perfect candidate for your team.

Jump to Your Level

Junior Developer ️ Mid-Level Developer Senior Developer

Junior Developer Challenges

1. Hello, World!

The traditional first program to verify a working setup.

<?php
echo "Hello, World!";
?>

2. Sum of an Array of Integers

A basic test of loops and array manipulation.

<?php
function sum(array $numbers): int {
    $total = 0;
    foreach ($numbers as $number) {
        $total += $number;
    }
    return $total;
}
?>

3. Reverse a String

A simple test of string manipulation.

<?php
function reverse(string $str): string {
    return strrev($str);
}
?>

4. Find the Largest Number in an Array

A fundamental algorithm using a simple loop.

<?php
function largest(array $numbers): int {
    $largest = $numbers[0];
    foreach ($numbers as $number) {
        if ($number > $largest) {
            $largest = $number;
        }
    }
    return $largest;
}
?>

5. Check if a String is a Palindrome

Tests string manipulation and comparison logic.

<?php
function isPalindrome(string $str): bool {
    return $str === strrev($str);
}
?>

6. FizzBuzz

The classic test of basic conditional logic and loops.

<?php
function fizzbuzz(int $n): void {
    for ($i = 1; $i <= $n; $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";
        }
    }
}
?>

7. Simple `class` for a `Person`

Introduces custom types and data organization.

<?php
class Person {
    public string $name;
    public int $age;

    public function __construct(string $name, int $age) {
        $this->name = $name;
        $this->age = $age;
    }
}
?>

8. Function that Returns an Associative Array

A simple function to demonstrate associative array creation.

<?php
function getPerson(): array {
    return [
        "name" => "John Doe",
        "age" => 30,
    ];
}
?>

9. Simple Loop to Print Numbers 1-10

A basic loop to demonstrate syntax.

<?php
for ($i = 1; $i <= 10; $i++) {
    echo "$i\n";
}
?>

10. Check if a Number is Positive, Negative, or Zero

Tests basic conditional logic.

<?php
function checkNumber(int $n): void {
    if ($n > 0) {
        echo "Positive\n";
    } elseif ($n < 0) {
        echo "Negative\n";
    } else {
        echo "Zero\n";
    }
}
?>

Mid-Level Developer Challenges

1. Word Count in a String using an Associative Array

Use an associative array to count the frequency of words in a text.

<?php
function wordCount(string $str): array {
    $words = str_word_count(strtolower($str), 1);
    return array_count_values($words);
}
?>

2. Implement a Simple Interface

A simple interface for a `Shape` with an `area` method.

<?php
interface Shape {
    public function area(): float;
}

class Circle implements Shape {
    private float $radius;

    public function __construct(float $radius) {
        $this->radius = $radius;
    }

    public function area(): float {
        return pi() * $this->radius * $this->radius;
    }
}
?>

3. JSON Serialization and Deserialization

Convert PHP objects to and from JSON using `json_encode` and `json_decode`.

<?php
class User {
    public string $name;
    public int $age;
}

$user = new User();
$user->name = "John Doe";
$user->age = 30;

$json = json_encode($user);
$user2 = json_decode($json, false, 512, JSON_THROW_ON_ERROR);
?>

4. Find the First Non-Repeating Character in a String

A common interview question that can be solved with an associative array.

<?php
function firstNonRepeatingCharacter(string $str): ?string {
    $counts = count_chars($str, 1);
    foreach (str_split($str) as $char) {
        if ($counts[ord($char)] === 1) {
            return $char;
        }
    }
    return null;
}
?>

5. Implement a Simple Trait

A simple trait for a `Logger`.

<?php
trait Logger {
    public function log(string $message): void {
        echo $message;
    }
}

class MyClass {
    use Logger;
}
?>

6. Error Handling with `try`/`catch`

A simple example of error handling with `try`/`catch`.

<?php
function doSomething(bool $fail): void {
    if ($fail) {
        throw new Exception("Something went wrong");
    }
}

try {
    doSomething(true);
} catch (Exception $e) {
    echo $e->getMessage();
}
?>

7. Use of Anonymous Functions

A simple example of an anonymous function.

<?php
$addOne = function (int $n): int {
    return $n + 1;
};

echo $addOne(1);
?>

8. Implement a Simple Command-Line Argument Parser

A simple command-line argument parser.

<?php
global $argv;

foreach ($argv as $arg) {
    echo "$arg\n";
}
?>

9. Read and Write to a File

A simple example of reading and writing to a file.

<?php
file_put_contents("foo.txt", "Hello, world!");
$contents = file_get_contents("foo.txt");
echo $contents;
?>

10. Implement a Simple Autoloader

A simple implementation of a PSR-4 autoloader.

<?php
spl_autoload_register(function (string $className): void {
    $file = str_replace('\\', DIRECTORY_SEPARATOR, $className) . '.php';
    if (file_exists($file)) {
        require $file;
    }
});
?>

Senior Developer Challenges

1. Implement a Simple Dependency Injection Container

A simple dependency injection container.

<?php
class Container {
    private array $services = [];

    public function set(string $name, callable $callable): void {
        $this->services[$name] = $callable;
    }

    public function get(string $name) {
        return $this->services[$name]($this);
    }
}
?>

2. Create a Simple Web Server with a Router

A simple web server with a router.

<?php
// Run with `php -S localhost:8000 router.php`
$uri = $_SERVER['REQUEST_URI'];

switch ($uri) {
    case '/':
        echo "Hello, world!";
        break;
    default:
        http_response_code(404);
        echo "404 Not Found";
}
?>

3. Implement a Simple Middleware Pattern

A simple middleware pattern.

<?php
interface Middleware {
    public function handle(callable $next);
}

class MyMiddleware implements Middleware {
    public function handle(callable $next) {
        echo "Before\n";
        $next();
        echo "After\n";
    }
}
?>

4. Write a Simple Composer Package

A simple Composer package.

// In composer.json
{
    "name": "my-vendor/my-package",
    "description": "My awesome package",
    "authors": [
        {
            "name": "My Name",
            "email": "[email protected]"
        }
    ],
    "require": {}
}

5. Implement a Simple Event Dispatcher

A simple event dispatcher.

<?php
class EventDispatcher {
    private array $listeners = [];

    public function addListener(string $eventName, callable $listener): void {
        $this->listeners[$eventName][] = $listener;
    }

    public function dispatch(string $eventName, $event): void {
        foreach ($this->listeners[$eventName] as $listener) {
            $listener($event);
        }
    }
}
?>

6. Use of Reflection to Inspect a Class

A simple example of using reflection to inspect a class.

<?php
$reflectionClass = new ReflectionClass(MyClass::class);
$methods = $reflectionClass->getMethods();
foreach ($methods as $method) {
    echo $method->getName() . "\n";
}
?>

7. Implement a Simple Concurrent Queue

A simple concurrent queue with `pthreads` or `Swoole`.

// This is a complex task that would require a lot of code.
// A full implementation would be too long for this format.

8. Write a Simple Key-Value Store with Caching

A simple key-value store with caching.

<?php
class KvStore {
    private array $data = [];
    private array $cache = [];

    public function set(string $key, $value): void {
        $this->data[$key] = $value;
        unset($this->cache[$key]);
    }

    public function get(string $key) {
        if (isset($this->cache[$key])) {
            return $this->cache[$key];
        }

        if (isset($this->data[$key])) {
            $this->cache[$key] = $this->data[$key];
            return $this->data[$key];
        }

        return null;
    }
}
?>

9. Implement a Simple State Machine

A simple state machine.

<?php
interface State {
    public function handle(Context $context): void;
}

class Context {
    private State $state;

    public function __construct(State $state) {
        $this->state = $state;
    }

    public function setState(State $state): void {
        $this->state = $state;
    }

    public function request(): void {
        $this->state->handle($this);
    }
}
?>

10. Create a Simple Build Script for a Project with Phing

A simple build script for a project with Phing.

<?xml version="1.0" encoding="UTF-8"?>
<project name="MyProject" default="build">
    <target name="build">
        <echo msg="Building..." />
    </target>
</project>

Tips to Prepare for PHP Coding Challenges

  • Master Array Functions: PHP has a vast and powerful library of array functions. Knowing them well can turn a complex loop into a single, readable line of code.
  • Embrace Modern OOP: Understand interfaces, traits, and abstract classes. Be prepared to discuss SOLID principles and design patterns.
  • Know Your PHP Standard Library (SPL): The SPL provides useful data structures like `SplQueue` and `SplHeap`. Using them can simplify your solutions.
  • Understand the HTTP Request Lifecycle: As a web language, many PHP challenges involve handling web requests. Know how to work with `$_GET`, `$_POST`, and headers.
  • Think About Security: Be mindful of common vulnerabilities like SQL injection and Cross-Site Scripting (XSS). Mentioning how to prevent them shows seniority.
  • Use Composer: The modern PHP ecosystem revolves around Composer. Understand how to manage dependencies and use autoloading.

Conclusion

PHP continues to be a dominant force on the web, and its modern versions are faster and more capable than ever. By practicing these challenges, you'll be well-prepared to tackle any interview and contribute to building the next generation of web applications. Happy coding!

Skip the interview marathon.

We pre-vet senior engineers across Asia using these exact questions and more. Get matched in 24 hours, $0 upfront.

Get Pre-Vetted Talent
WhatsApp