100 PHP practice problems with solutions

Feeling stuck trying to turn PHP syntax into real, working web applications? That frustrating gap between watching tutorials and building something on your own ends here. This post brings you 100 PHP practice problems with clear, step-by-step solutions designed to make your skills truly stick.

You’ll start with the essentials—variables, arrays, loops, and forms—then confidently move on to sessions, file handling, database integration with MySQL, object-oriented PHP, and basic security practices. Each problem is written in plain, simple language. Try solving it yourself first, then check the solution and fully understand the reasoning behind the code.

Why is practice so important? Because web development is a hands-on craft. Every challenge you complete builds real muscle memory, sharpens your debugging sense, and turns scattered knowledge into the ability to build dynamic websites from scratch. This is exactly what separates developers who just “know PHP” from those who can confidently create and launch projects—and it’s the secret to shining in interviews or freelance gigs.

Pick a problem, start coding, and feel that amazing “I’m really building this!” moment. Your journey to mastering PHP starts now.

Also try it: 100 Java practice problems with solutions

1. Write a PHP script that prints “Hello, World!”

php

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

2. Write a PHP script to declare two integer variables and print their sum.

php

<?php
$a = 10;
$b = 20;
echo "Sum: " . ($a + $b);
?>

3. Write a PHP script that takes a number as input and prints whether it is even or odd.

php

<?php
$num = 7;
if ($num % 2 == 0) {
    echo "$num is even";
} else {
    echo "$num is odd";
}
?>

4. Write a PHP script to print numbers from 1 to 10 using a for loop.

php

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

5. Write a PHP script to calculate the factorial of a number (e.g., 5).

php

<?php
$n = 5;
$fact = 1;
for ($i = 1; $i <= $n; $i++) {
    $fact *= $i;
}
echo "Factorial of $n is $fact";
?>

6. Write a PHP script to reverse a string (e.g., “Hello” → “olleH”).

php

<?php
$str = "Hello";
$rev = strrev($str);
echo $rev;
?>

7. Write a PHP script to check if a string is a palindrome (e.g., “radar”).

php

<?php
$str = "radar";
if ($str == strrev($str)) {
    echo "$str is palindrome";
} else {
    echo "$str is not palindrome";
}
?>

8. Write a PHP script to find the largest number in an array [3,7,1,9,4].

php

<?php
$arr = [3, 7, 1, 9, 4];
$max = max($arr);
echo "Largest: $max";
?>

9. Write a PHP script to calculate the sum of all elements in an array [2,4,6,8].

php

<?php
$arr = [2, 4, 6, 8];
$sum = array_sum($arr);
echo "Sum: $sum";
?>

10. Write a PHP script to count the number of vowels in a string “Hello World”.

php

<?php
$str = "Hello World";
$vowels = ['a','e','i','o','u','A','E','I','O','U'];
$count = 0;
for ($i = 0; $i < strlen($str); $i++) {
    if (in_array($str[$i], $vowels)) $count++;
}
echo "Vowels: $count";
?>

11. Write a PHP script to print the Fibonacci series up to 10 terms.

php

<?php
$n = 10;
$a = 0; $b = 1;
echo "Fibonacci: ";
for ($i = 0; $i < $n; $i++) {
    echo $a . " ";
    $next = $a + $b;
    $a = $b;
    $b = $next;
}
?>

12. Write a PHP script to check if a number is prime (e.g., 17).

php

<?php
function isPrime($num) {
    if ($num <= 1) return false;
    for ($i = 2; $i <= sqrt($num); $i++) {
        if ($num % $i == 0) return false;
    }
    return true;
}
$num = 17;
echo $num . (isPrime($num) ? " is prime" : " is not prime");
?>

13. Write a PHP script to remove duplicate values from an array [1,2,2,3,4,4,5].

php

<?php
$arr = [1,2,2,3,4,4,5];
$unique = array_unique($arr);
print_r($unique);
?>

14. Write a PHP script to sort an array [5,2,8,1,3] in ascending order.

php

<?php
$arr = [5,2,8,1,3];
sort($arr);
print_r($arr);
?>

15. Write a PHP script to find the second largest number in an array [10,20,4,45,99].

php

<?php
$arr = [10,20,4,45,99];
rsort($arr);
echo "Second largest: " . $arr[1];
?>

16. Write a PHP function that returns the greatest common divisor (GCD) of two numbers.

php

<?php
function gcd($a, $b) {
    while ($b != 0) {
        $temp = $b;
        $b = $a % $b;
        $a = $temp;
    }
    return $a;
}
echo gcd(48, 18);
?>

17. Write a PHP class Rectangle with properties length and width, and a method to compute area.

php

<?php
class Rectangle {
    public $length;
    public $width;
    public function __construct($l, $w) {
        $this->length = $l;
        $this->width = $w;
    }
    public function area() {
        return $this->length * $this->width;
    }
}
$rect = new Rectangle(5, 3);
echo "Area: " . $rect->area();
?>

18. Write a PHP script to demonstrate function overloading using default parameters.

php

<?php
function add($a, $b = 0) {
    return $a + $b;
}
echo add(5, 10) . "\n";
echo add(5);
?>

19. Write a PHP script that creates a Student class with name and roll number, and prints details.

php

<?php
class Student {
    public $name;
    public $roll;
    public function __construct($name, $roll) {
        $this->name = $name;
        $this->roll = $roll;
    }
    public function display() {
        echo "Name: {$this->name}, Roll: {$this->roll}";
    }
}
$s = new Student("Alice", 101);
$s->display();
?>

20. Write a PHP script that demonstrates inheritance: parent class Animal and child Dog.

php

<?php
class Animal {
    public function sound() {
        return "Animal makes sound";
    }
}
class Dog extends Animal {
    public function sound() {
        return "Dog barks";
    }
}
$dog = new Dog();
echo $dog->sound();
?>

21. Write a PHP script that uses an interface Drawable with a method draw().

php

<?php
interface Drawable {
    public function draw();
}
class Circle implements Drawable {
    public function draw() {
        echo "Drawing Circle";
    }
}
$c = new Circle();
$c->draw();
?>

22. Write a PHP script that handles division by zero using try-catch.

php

<?php
try {
    $result = 10 / 0;
} catch (DivisionByZeroError $e) {
    echo "Cannot divide by zero!";
}
?>

23. Write a PHP script that reads a line from standard input and prints its length.

php

<?php
echo "Enter a string: ";
$line = trim(fgets(STDIN));
echo "Length: " . strlen($line);
?>

24. Write a PHP script to count the number of words in a sentence using str_word_count.

php

<?php
$sentence = "The quick brown fox";
$count = str_word_count($sentence);
echo "Word count: $count";
?>

25. Write a PHP script to convert an array of strings to uppercase.

php

<?php
$words = ["apple", "banana", "cherry"];
$upper = array_map('strtoupper', $words);
print_r($upper);
?>

26. Write a PHP script that uses a for loop to print numbers from 1 to 10 in reverse.

php

<?php
for ($i = 10; $i >= 1; $i--) {
    echo $i . " ";
}
?>

27. Write a PHP script to check if a string contains only digits.

php

<?php
$str = "12345";
if (ctype_digit($str)) {
    echo "Only digits";
} else {
    echo "Contains non-digits";
}
?>

28. Write a PHP script to find common elements between two arrays [1,2,3,4] and [3,4,5,6].

php

<?php
$arr1 = [1,2,3,4];
$arr2 = [3,4,5,6];
$common = array_intersect($arr1, $arr2);
print_r($common);
?>

29. Write a PHP script to square each element of an array using array_map.

php

<?php
$nums = [1,2,3,4];
$squared = array_map(function($n) { return $n * $n; }, $nums);
print_r($squared);
?>

30. Write a PHP script to write a string to a file named “output.txt” and then read it.

php

<?php
file_put_contents("output.txt", "Hello PHP");
$content = file_get_contents("output.txt");
echo $content;
?>

31. Write a PHP recursive function to compute factorial.

php

<?php
function factorial($n) {
    if ($n <= 1) return 1;
    return $n * factorial($n-1);
}
echo factorial(5);
?>

32. Write a PHP script to print the multiplication table for a given number (e.g., 7).

php

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

33. Write a PHP script to remove all whitespace from a string.

php

<?php
$str = " Hello World ";
$clean = str_replace(' ', '', $str);
echo $clean;
?>

34. Write a PHP script to swap two numbers without using a third variable.

php

<?php
$a = 5; $b = 10;
list($a, $b) = [$b, $a];
echo "a=$a, b=$b";
?>

35. Write a PHP script to create an associative array of names and ages, then print each.

php

<?php
$ages = ["Alice" => 25, "Bob" => 30];
foreach ($ages as $name => $age) {
    echo "$name: $age\n";
}
?>

36. Write a PHP script to sort an array of strings alphabetically.

php

<?php
$words = ["banana", "apple", "cherry"];
sort($words);
print_r($words);
?>

37. Write a PHP script to find the first non-repeated character in a string “swiss”.

php

<?php
$str = "swiss";
$len = strlen($str);
for ($i = 0; $i < $len; $i++) {
    if (substr_count($str, $str[$i]) == 1) {
        echo $str[$i];
        break;
    }
}
?>

38. Write a PHP script to check if two strings are anagrams (e.g., “listen”, “silent”).

php

<?php
function areAnagrams($s1, $s2) {
    return count_chars($s1, 1) == count_chars($s2, 1);
}
$s1 = "listen"; $s2 = "silent";
echo areAnagrams($s1, $s2) ? "Anagrams" : "Not anagrams";
?>

39. Write a PHP script that uses a static variable to count how many times a function is called.

php

<?php
function counter() {
    static $count = 0;
    $count++;
    echo "Called $count times\n";
}
counter();
counter();
?>

40. Write a PHP script that demonstrates the use of date() function to print current date.

php

<?php
echo date("Y-m-d H:i:s");
?>

41. Write a PHP script to rotate an array to the left by k positions (k=2).

php

<?php
$arr = [1,2,3,4,5];
$k = 2;
$rotated = array_merge(array_slice($arr, $k), array_slice($arr, 0, $k));
print_r($rotated);
?>

42. Write a PHP script to find the missing number in an array of 1..n (e.g., {1,2,3,5} missing 4).

php

<?php
$arr = [1,2,3,5];
$n = 5;
$expected = $n * ($n+1)/2;
$actual = array_sum($arr);
echo "Missing: " . ($expected - $actual);
?>

43. Write a PHP script to count occurrences of each character in a string using count_chars.

php

<?php
$str = "abracadabra";
$freq = count_chars($str, 1);
foreach ($freq as $ascii => $count) {
    echo chr($ascii) . ": $count\n";
}
?>

44. Write a PHP script to merge two sorted arrays into one sorted array.

php

<?php
$a = [1,3,5];
$b = [2,4,6];
$merged = array_merge($a, $b);
sort($merged);
print_r($merged);
?>

45. Write a PHP script to compute the power of a number using recursion (x^n).

php

<?php
function power($base, $exp) {
    if ($exp == 0) return 1;
    return $base * power($base, $exp-1);
}
echo power(2, 5);
?>

46. Write a PHP script to check if a string is a valid email address (simple regex).

php

<?php
$email = "test@example.com";
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo "Valid email";
} else {
    echo "Invalid email";
}
?>

47. Write a PHP script that uses explode and implode to reverse words in a sentence.

php

<?php
$sentence = "Hello world from PHP";
$words = explode(" ", $sentence);
$reversed = implode(" ", array_reverse($words));
echo $reversed;
?>

48. Write a PHP script that generates a random integer between 1 and 100.

php

<?php
echo rand(1, 100);
?>

Also try it: 100 Ruby practice problems with solutions

49. Write a PHP script that reads a CSV file and prints its rows (assume file exists).

php

<?php
if (($handle = fopen("data.csv", "r")) !== false) {
    while (($data = fgetcsv($handle)) !== false) {
        print_r($data);
    }
    fclose($handle);
}
?>

50. Write a PHP script that implements a simple calculator using switch.

php

<?php
$a = 10; $b = 5; $op = '+';
switch ($op) {
    case '+': $result = $a + $b; break;
    case '-': $result = $a - $b; break;
    case '*': $result = $a * $b; break;
    case '/': $result = $a / $b; break;
    default: $result = "Invalid operator";
}
echo "Result: $result";
?>

51. Write a PHP script that uses header() to redirect to another page (simulate).

php

<?php
// header("Location: https://example.com");
// exit;
echo "Redirect would happen here";
?>

52. Write a PHP script that sets a cookie and then reads it.

php

<?php
setcookie("user", "John", time()+3600);
if (isset($_COOKIE["user"])) {
    echo "Welcome " . $_COOKIE["user"];
} else {
    echo "Cookie not set";
}
?>

53. Write a PHP script that starts a session and stores a value.

php

<?php
session_start();
$_SESSION["name"] = "Alice";
echo "Session variable set";
?>

54. Write a PHP script to get the current script’s filename using __FILE__ and basename.

php

<?php
echo basename(__FILE__);
?>

55. Write a PHP script to check if a variable is set and not null using isset.

php

<?php
$var = "Hello";
if (isset($var)) {
    echo "Variable is set";
} else {
    echo "Not set";
}
?>

56. Write a PHP script to calculate the average of an array of numbers.

php

<?php
$nums = [10, 20, 30, 40];
$avg = array_sum($nums) / count($nums);
echo "Average: $avg";
?>

57. Write a PHP script to find the intersection of two arrays using array_intersect.

php

<?php
$a = [1,2,3,4];
$b = [3,4,5,6];
$intersect = array_intersect($a, $b);
print_r($intersect);
?>

58. Write a PHP script to find the union of two arrays (no duplicates) using array_merge and array_unique.

php

<?php
$a = [1,2,3];
$b = [3,4,5];
$union = array_unique(array_merge($a, $b));
print_r($union);
?>

59. Write a PHP script that uses json_encode and json_decode to convert array to JSON and back.

php

<?php
$data = ["name" => "John", "age" => 30];
$json = json_encode($data);
echo "JSON: $json\n";
$decoded = json_decode($json, true);
print_r($decoded);
?>

60. Write a PHP script that uses preg_match to find if a string contains a digit.

php

<?php
$str = "Hello123";
if (preg_match('/\d/', $str)) {
    echo "Contains digit";
} else {
    echo "No digit";
}
?>

61. Write a PHP script that reads a directory and lists all files using scandir.

php

<?php
$files = scandir(".");
foreach ($files as $file) {
    if ($file != "." && $file != "..") {
        echo $file . "\n";
    }
}
?>

62. Write a PHP script to rename a file from “old.txt” to “new.txt”.

php

<?php
rename("old.txt", "new.txt");
echo "File renamed";
?>

63. Write a PHP script to copy a file from “source.txt” to “destination.txt”.

php

<?php
copy("source.txt", "destination.txt");
echo "File copied";
?>

64. Write a PHP script to delete a file named “temp.txt”.

php

<?php
if (file_exists("temp.txt")) {
    unlink("temp.txt");
    echo "File deleted";
}
?>

65. Write a PHP script that uses error_log to write a custom error message to the log.

php

<?php
error_log("Custom error message", 0);
echo "Error logged";
?>

66. Write a PHP script that creates a directory and then removes it.

php

<?php
mkdir("testdir");
rmdir("testdir");
echo "Directory created and removed";
?>

67. Write a PHP script to get the size of a file in bytes using filesize.

php

<?php
$size = filesize("input.txt");
echo "File size: $size bytes";
?>

68. Write a PHP script that uses parse_url to extract domain from a URL.

php

<?php
$url = "https://www.example.com/path";
$parts = parse_url($url);
echo "Domain: " . $parts['host'];
?>

69. Write a PHP script that uses http_build_query to create query string from array.

php

<?php
$data = ["name" => "John", "age" => 30];
$query = http_build_query($data);
echo $query;
?>

70. Write a PHP script that implements a simple rate limiter using file-based counter.

php

<?php
$file = "counter.txt";
$limit = 5;
$current = (int)file_get_contents($file);
if ($current >= $limit) {
    echo "Rate limit exceeded";
} else {
    file_put_contents($file, $current+1);
    echo "Request allowed";
}
?>

71. Write a PHP script to generate a UUID (version 4) using uniqid and random bytes.

php

<?php
function uuid() {
    return sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
        mt_rand(0, 0xffff), mt_rand(0, 0xffff),
        mt_rand(0, 0xffff),
        mt_rand(0, 0x0fff) | 0x4000,
        mt_rand(0, 0x3fff) | 0x8000,
        mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
    );
}
echo uuid();
?>

72. Write a PHP script to throw a custom exception and catch it.

php

<?php
class MyException extends Exception {}
try {
    throw new MyException("Something went wrong");
} catch (MyException $e) {
    echo "Caught: " . $e->getMessage();
}
?>

73. Write a PHP script that uses array_reduce to find the product of all array elements.

php

<?php
$nums = [2,3,4];
$product = array_reduce($nums, function($carry, $item) {
    return $carry * $item;
}, 1);
echo $product;
?>

74. Write a PHP script that uses array_filter to remove even numbers from an array.

php

<?php
$nums = [1,2,3,4,5,6];
$odd = array_filter($nums, function($n) {
    return $n % 2 != 0;
});
print_r($odd);
?>

75. Write a PHP script to find the longest word in a string using str_word_count.

php

<?php
$text = "The quick brown fox jumps over the lazy dog";
$words = str_word_count($text, 1);
$longest = '';
foreach ($words as $word) {
    if (strlen($word) > strlen($longest)) {
        $longest = $word;
    }
}
echo "Longest word: $longest";
?>

76. Write a PHP script that uses password_hash and password_verify to hash a password.

php

<?php
$password = "mysecret";
$hash = password_hash($password, PASSWORD_DEFAULT);
echo "Hash: $hash\n";
if (password_verify($password, $hash)) {
    echo "Password verified";
}
?>

77. Write a PHP script that uses curl to make a GET request (if curl extension is available).

php

<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.example.com/data");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
echo $response;
?>

78. Write a PHP script that uses fopenfwrite, and fclose to write to a file.

php

<?php
$fp = fopen("test.txt", "w");
fwrite($fp, "Hello, file!");
fclose($fp);
echo "File written";
?>

79. Write a PHP script that reads a file line by line using fgets.

php

<?php
$fp = fopen("test.txt", "r");
while (($line = fgets($fp)) !== false) {
    echo $line;
}
fclose($fp);
?>

80. Write a PHP script that uses serialize and unserialize to store an array.

php

<?php
$data = ["name" => "John", "age" => 30];
$serialized = serialize($data);
file_put_contents("data.txt", $serialized);
$restored = unserialize(file_get_contents("data.txt"));
print_r($restored);
?>

81. Write a PHP script that uses get_declared_classes to list all declared classes.

php

<?php
$classes = get_declared_classes();
print_r(array_slice($classes, 0, 10)); // show first 10
?>

82. Write a PHP script that implements a simple autoloader using spl_autoload_register.

php

<?php
spl_autoload_register(function($class) {
    include $class . '.php';
});
// If MyClass.php exists, new MyClass() would work
echo "Autoloader registered";
?>

83. Write a PHP script that uses trait to share methods between classes.

php

<?php
trait Logger {
    public function log($msg) {
        echo "Log: $msg\n";
    }
}
class User {
    use Logger;
}
$u = new User();
$u->log("User created");
?>

Also try it: 100 PostgreSQL practice problems with solutions

84. Write a PHP script that uses foreach to iterate over an associative array and display key-value pairs.

php

<?php
$person = ["name" => "Alice", "age" => 25];
foreach ($person as $key => $value) {
    echo "$key: $value\n";
}
?>

85. Write a PHP script to generate a random string of given length using random_bytes.

php

<?php
function randomString($length) {
    return bin2hex(random_bytes($length / 2));
}
echo randomString(10);
?>

86. Write a PHP script that uses array_column to extract a column from a 2D array.

php

<?php
$users = [
    ["id" => 1, "name" => "John"],
    ["id" => 2, "name" => "Jane"]
];
$names = array_column($users, "name");
print_r($names);
?>

87. Write a PHP script that uses array_search to find the index of a value in an array.

php

<?php
$fruits = ["apple", "banana", "cherry"];
$index = array_search("banana", $fruits);
echo "Index: $index";
?>

88. Write a PHP script that uses in_array to check if a value exists in an array.

php

<?php
$fruits = ["apple", "banana", "cherry"];
if (in_array("banana", $fruits)) {
    echo "Found";
} else {
    echo "Not found";
}
?>

89. Write a PHP script that uses array_keys to get all keys of an associative array.

php

<?php
$person = ["name" => "Alice", "age" => 25];
$keys = array_keys($person);
print_r($keys);
?>

90. Write a PHP script that uses array_values to get all values of an array.

php

<?php
$person = ["name" => "Alice", "age" => 25];
$values = array_values($person);
print_r($values);
?>

91. Write a PHP script that uses array_merge to combine two arrays.

php

<?php
$a = [1,2,3];
$b = [4,5,6];
$combined = array_merge($a, $b);
print_r($combined);
?>

92. Write a PHP script that uses array_diff to find elements in first array not in second.

php

<?php
$a = [1,2,3,4];
$b = [3,4,5,6];
$diff = array_diff($a, $b);
print_r($diff);
?>

93. Write a PHP script that uses array_sum and array_product on an array.

php

<?php
$nums = [2,3,4];
echo "Sum: " . array_sum($nums) . "\n";
echo "Product: " . array_product($nums);
?>

94. Write a PHP script that uses range to create an array of numbers from 1 to 10.

php

<?php
$numbers = range(1, 10);
print_r($numbers);
?>

95. Write a PHP script that uses shuffle to randomize the order of an array.

php

<?php
$cards = [1,2,3,4,5];
shuffle($cards);
print_r($cards);
?>
**

96. Write a PHP script that uses `usort` to sort an array of associative arrays by a field.**  
```php
<?php
$users = [
    ["name" => "Alice", "age" => 25],
    ["name" => "Bob", "age" => 20]
];
usort($users, function($a, $b) {
    return $a['age'] <=> $b['age'];
});
print_r($users);
?>

97. Write a PHP script that uses DateTime class to calculate the difference between two dates.

php

<?php
$date1 = new DateTime("2024-01-01");
$date2 = new DateTime("2024-12-31");
$diff = $date1->diff($date2);
echo "Difference: " . $diff->days . " days";
?>

98. Write a PHP script that uses ReflectionClass to inspect a class.

php

<?php
class Example {}
$reflect = new ReflectionClass('Example');
echo "Class name: " . $reflect->getName();
?>

99. Write a PHP script that uses preg_replace to remove all non-alphanumeric characters from a string.

php

<?php
$str = "Hello, World! 123.";
$clean = preg_replace('/[^a-zA-Z0-9]/', '', $str);
echo $clean;
?>

100. Write a PHP script that implements a simple form processor (GET method).

php

<?php
if (isset($_GET['name'])) {
    echo "Hello, " . htmlspecialchars($_GET['name']);
} else {
    echo '<form method="get"><input type="text" name="name"><button>Submit</button></form>';
}
?>

Final Thought

One hundred problems later, and here you are — still standing, but now much stronger. You didn’t just read PHP. You wrote it, debugged it, and watched it run. From simple forms to database queries, from sessions to object‑oriented logic, every challenge quietly built a layer of real confidence that tutorials alone can’t give.

PHP has been powering the web for decades, and now you know why — it’s practical, forgiving, and incredibly useful when you truly understand it. The muscle memory you built here will carry into every real project, every freelancing gig, and every interview question that comes your way.

Save this page. Come back when you feel rusty. Push yourself to build something fresh using what you practiced. And most of all, be proud — you’ve moved from “I know PHP” to “I can build with PHP.” That’s a huge leap. Happy coding, and keep that momentum alive! 

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top