PHP Exercises

πŸš€ PHP Exercises – Practice PHP with Fun Challenges

The best way to master PHP? Practice, practice, practice! 🎯 Below are hands-on exercises covering variables, loops, functions, arrays, and OOP. Test your skills and improve your PHP coding!


πŸ“ Basic PHP Exercises

βœ… Exercise 1: Display a Message

Create a PHP script to print Hello, PHP World! on the screen.

<?php
// Your code here
echo "Hello, PHP World!";
?>

Try It Now


βœ… Exercise 2: Simple Calculator

Write a PHP function that takes two numbers and an operator (+, -, *, /) and returns the result.

<?php
function calculator($num1, $num2, $operator) {
    switch($operator) {
        case '+': return $num1 + $num2;
        case '-': return $num1 - $num2;
        case '*': return $num1 * $num2;
        case '/': return ($num2 != 0) ? $num1 / $num2 : "Cannot divide by zero!";
        default: return "Invalid operator!";
    }
}

// Test the function
echo calculator(10, 5, '+'); // Output: 15
?>

Try It Now


πŸ“ Loop Exercises

βœ… Exercise 3: Print Even Numbers

Write a PHP script to print even numbers from 1 to 20 using a loop.

<?php
for ($i = 1; $i <= 20; $i++) {
    if ($i % 2 == 0) {
        echo $i . "<br>";
    }
}
?>

Try It Now


βœ… Exercise 4: Reverse a String

Create a function that takes a string and returns it reversed.

<?php
function reverseString($str) {
    return strrev($str);
}

// Test
echo reverseString("PHP is fun!"); // Output: !nuf si PHP
?>

Try It Now


πŸ“ Array & Function Exercises

βœ… Exercise 5: Find the Maximum Number

Write a function that takes an array of numbers and returns the maximum value.

<?php
function findMax($arr) {
    return max($arr);
}

// Test
echo findMax([3, 5, 9, 2, 8]); // Output: 9
?>

Try It Now


πŸ“ Object-Oriented PHP (OOP) Exercises

βœ… Exercise 6: Create a Class

Write a PHP class Car with properties brand and color, and a method to display them.

<?php
class Car {
    public $brand;
    public $color;

    function __construct($brand, $color) {
        $this->brand = $brand;
        $this->color = $color;
    }

    function showCar() {
        return "This car is a " . $this->color . " " . $this->brand . ".";
    }
}

// Create an object
$myCar = new Car("Toyota", "Red");
echo $myCar->showCar(); // Output: This car is a Red Toyota.
?>

Try It Now


🎯 More Challenges!

  • πŸ›  Create a function that checks if a number is prime.
  • πŸ›  Write a script that counts the occurrences of a word in a string.
  • πŸ›  Implement a basic login system using sessions.
  • πŸ›  Create a PHP script to generate a random password.