π 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!"; ?>
β 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
?>
π 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>";
}
}
?>
β 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
?>
π 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
?>
π 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.
?>
π― 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.