PHP Code Examples

A comprehensive collection of PHP code snippets and examples to boost your development skills

Explore Examples

PHP Basics

Fundamental concepts and syntax examples

Variables & Echo
<?php // Defining variables $name = "John Doe"; $age = 30; $isActive = true; $salary = 75000.50; // Outputting variables echo "Name: " . $name . "<br>"; echo "Age: $age years old<br>"; echo "Active status: " . ($isActive ? "Active" : "Inactive") . "<br>"; echo "Salary: $" . number_format($salary, 2); ?>
Basic variable declaration and string output with concatenation and interpolation.
Control Structures
<?php $score = 85; // If-else statement if ($score >= 90) { echo "Grade: A"; } elseif ($score >= 80) { echo "Grade: B"; } elseif ($score >= 70) { echo "Grade: C"; } elseif ($score >= 60) { echo "Grade: D"; } else { echo "Grade: F"; } // Switch statement $day = date("l"); switch ($day) { case "Monday": echo "<br>Start of work week"; break; case "Friday": echo "<br>End of work week"; break; case "Saturday": case "Sunday": echo "<br>Weekend!"; break; default: echo "<br>Midweek"; } ?>
Examples of if-else statements and switch case for flow control.
Functions
<?php // Simple function function greet($name) { return "Hello, $name!"; } // Function with default parameter function calculateTotal($prices, $taxRate = 0.08) { $subtotal = array_sum($prices); $tax = $subtotal * $taxRate; return $subtotal + $tax; } // Using arrow functions (PHP 7.4+) $multiply = fn($a, $b) => $a * $b; // Using the functions echo greet("Maria") . "<br>"; $prices = [10.99, 24.50, 35.00]; echo "Total with tax: $" . calculateTotal($prices) . "<br>"; echo "5 × 4 = " . $multiply(5, 4); ?>
Creating and using functions, including default parameters and arrow functions.

Arrays & Loops

Working with data collections and iteration

Array Manipulation
<?php // Indexed array $fruits = ["apple", "banana", "orange", "mango"]; echo $fruits[1] . "<br>"; // banana // Associative array $person = [ "name" => "Alice Smith", "age" => 28, "email" => "[email protected]", "hobbies" => ["reading", "hiking", "photography"] ]; echo $person["name"] . " is " . $person["age"] . " years old<br>"; echo "Favorite hobby: " . $person["hobbies"][0] . "<br>"; // Array functions $numbers = [5, 2, 8, 1, 9]; sort($numbers); echo "Sorted: " . implode(", ", $numbers) . "<br>"; $sum = array_sum($numbers); echo "Sum: $sum<br>"; $filteredNumbers = array_filter($numbers, fn($n) => $n > 5); echo "Numbers > 5: " . implode(", ", $filteredNumbers) . "<br>"; $doubledNumbers = array_map(fn($n) => $n * 2, $numbers); echo "Doubled: " . implode(", ", $doubledNumbers); ?>
Creating and manipulating indexed and associative arrays with built-in functions.
Loops
<?php // For loop echo "For loop:<br>"; for ($i = 1; $i <= 5; $i++) { echo "$i "; } echo "<br><br>"; // While loop echo "While loop:<br>"; $counter = 1; while ($counter <= 5) { echo "$counter "; $counter++; } echo "<br><br>"; // Do-while loop echo "Do-while loop:<br>"; $j = 1; do { echo "$j "; $j++; } while ($j <= 5); echo "<br><br>"; // Foreach loop with indexed array echo "Foreach with indexed array:<br>"; $colors = ["red", "green", "blue", "yellow"]; foreach ($colors as $color) { echo "$color "; } echo "<br><br>"; // Foreach loop with associative array echo "Foreach with associative array:<br>"; $capitals = [ "USA" => "Washington D.C.", "UK" => "London", "France" => "Paris", "Japan" => "Tokyo" ]; foreach ($capitals as $country => $capital) { echo "The capital of $country is $capital<br>"; } ?>
Various loop structures for iterating through data.

Object-Oriented Programming

Classes, objects, inheritance, and more

Classes & Objects
<?php class User { // Properties private $username; private $email; protected $role = "member"; // Constructor public function __construct($username, $email) { $this->username = $username; $this->email = $email; } // Methods public function getUsername() { return $this->username; } public function getEmail() { return $this->email; } public function getRole() { return $this->role; } public function setEmail($email) { // Basic validation if (filter_var($email, FILTER_VALIDATE_EMAIL)) { $this->email = $email; return true; } return false; } // Static method public static function validateUsername($username) { return strlen($username) >= 4; } } // Creating an object $user = new User("johndoe", "[email protected]"); echo "Username: " . $user->getUsername() . "<br>"; echo "Email: " . $user->getEmail() . "<br>"; echo "Role: " . $user->getRole() . "<br>"; // Using static method $validUsername = User::validateUsername("jane"); echo "Is 'jane' a valid username? " . ($validUsername ? "Yes" : "No") . "<br>"; ?>
Implementing classes with properties, methods, and constructor in PHP.
Inheritance & Polymorphism
<?php // Base class class Vehicle { protected $make; protected $model; protected $year; public function __construct($make, $model, $year) { $this->make = $make; $this->model = $model; $this->year = $year; } public function getInfo() { return "{$this->year} {$this->make} {$this->model}"; } public function startEngine() { return "Engine started!"; } } // Derived class class Car extends Vehicle { private $numDoors; public function __construct($make, $model, $year, $numDoors) { parent::__construct($make, $model, $year); $this->numDoors = $numDoors; } public function getInfo() { return parent::getInfo() . " with {$this->numDoors} doors"; } public function startEngine() { return "Car engine purrs quietly"; } } // Another derived class class Motorcycle extends Vehicle { private $type; public function __construct($make, $model, $year, $type) { parent::__construct($make, $model, $year); $this->type = $type; } public function getInfo() { return parent::getInfo() . " ({$this->type})"; } public function startEngine() { return "Motorcycle engine roars loudly!"; } } // Using the classes $car = new Car("Toyota", "Camry", 2022, 4); echo $car->getInfo() . "<br>"; echo $car->startEngine() . "<br><br>"; $motorcycle = new Motorcycle("Harley-Davidson", "Street Glide", 2021, "Cruiser"); echo $motorcycle->getInfo() . "<br>"; echo $motorcycle->startEngine() . "<br>"; ?>
Implementing inheritance and method overriding for polymorphic behavior.
Interfaces & Traits
<?php // Interface interface Payable { public function calculatePay(); public function getPaymentInfo(); } // Trait trait Logger { private $logMessages = []; public function log($message) { $timestamp = date("Y-m-d H:i:s"); $this->logMessages[] = "[$timestamp] $message"; } public function getLogs() { return $this->logMessages; } } // Class implementing interface and using trait class Employee implements Payable { use Logger; private $name; private $hourlyRate; private $hoursWorked; public function __construct($name, $hourlyRate, $hoursWorked) { $this->name = $name; $this->hourlyRate = $hourlyRate; $this->hoursWorked = $hoursWorked; $this->log("Created employee: $name"); } public function calculatePay() { $pay = $this->hourlyRate * $this->hoursWorked; $this->log("Calculated pay for {$this->name}: \${$pay}"); return $pay; } public function getPaymentInfo() { return "{$this->name} - \${$this->hourlyRate}/hour × {$this->hoursWorked} hours"; } } // Using the class $employee = new Employee("Sarah Johnson", 25.50, 40); echo "Payment info: " . $employee->getPaymentInfo() . "<br>"; echo "Pay: $" . $employee->calculatePay() . "<br><br>"; echo "Logs:<br>"; foreach ($employee->getLogs() as $log) { echo $log . "<br>"; } ?>
Using interfaces for contracts and traits for code reuse.

Database Operations

Connecting and working with databases

PDO Database Connection
<?php // Database configuration $host = "localhost"; $dbname = "example_db"; $username = "db_user"; $password = "db_password"; try { // Create PDO instance $pdo = new PDO( "mysql:host=$host;dbname=$dbname;charset=utf8", $username, $password, [ PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, PDO::ATTR_EMULATE_PREPARES => false ] ); echo "Connected successfully to database<br>"; } catch (PDOException $e) { die("Connection failed: " . $e->getMessage()); } // Example query try { $stmt = $pdo->query("SELECT VERSION() as version"); $row = $stmt->fetch(); echo "Database version: " . $row["version"]; } catch (PDOException $e) { echo "Query failed: " . $e->getMessage(); } ?>
Establishing a secure database connection using PDO.
CRUD Operations
<?php /* Assuming we have a valid $pdo connection from previous example */ // CREATE - Insert new user function createUser($pdo, $username, $email, $password) { $hashedPassword = password_hash($password, PASSWORD_DEFAULT); $sql = "INSERT INTO users (username, email, password_hash, created_at) VALUES (:username, :email, :password_hash, NOW())"; try { $stmt = $pdo->prepare($sql); $stmt->execute([ ":username" => $username, ":email" => $email, ":password_hash" => $hashedPassword ]); return $pdo->lastInsertId(); } catch (PDOException $e) { // Log error and return false in production echo "Error creating user: " . $e->getMessage(); return false; } } // READ - Get user by ID function getUserById($pdo, $userId) { $sql = "SELECT id, username, email, created_at FROM users WHERE id = :id"; try { $stmt = $pdo->prepare($sql); $stmt->execute([":id" => $userId]); return $stmt->fetch(); } catch (PDOException $e) { echo "Error fetching user: " . $e->getMessage(); return false; } } // UPDATE - Update user email function updateUserEmail($pdo, $userId, $newEmail) { $sql = "UPDATE users SET email = :email, updated_at = NOW() WHERE id = :id"; try { $stmt = $pdo->prepare($sql); $stmt->execute([ ":email" => $newEmail, ":id" => $userId ]); return $stmt->rowCount() > 0; } catch (PDOException $e) { echo "Error updating user: " . $e->getMessage(); return false; } } // DELETE - Delete user function deleteUser($pdo, $userId) { $sql = "DELETE FROM users WHERE id = :id"; try { $stmt = $pdo->prepare($sql); $stmt->execute([":id" => $userId]); return $stmt->rowCount() > 0; } catch (PDOException $e) { echo "Error deleting user: " . $e->getMessage(); return false; } } // Example usage (commented out) /* // Create a new user $newUserId = createUser($pdo, "newuser", "[email protected]", "secure_password123"); echo "Created user with ID: $newUserId<br>"; // Get the user $user = getUserById($pdo, $newUserId); echo "Username: " . $user["username"] . "<br>"; // Update user email $updated = updateUserEmail($pdo, $newUserId, "[email protected]"); echo "User updated: " . ($updated ? "Yes" : "No") . "<br>"; // Delete user $deleted = deleteUser($pdo, $newUserId); echo "User deleted: " . ($deleted ? "Yes" : "No") . "<br>"; */ ?>
Create, Read, Update, Delete (CRUD) operations using prepared statements.

Contact Form Example

PHP form processing with validation

Form Processing Code
<?php // Initialize variables $name = $email = $message = ""; $nameErr = $emailErr = $messageErr = ""; $formSubmitted = false; // Form processing if ($_SERVER["REQUEST_METHOD"] == "POST") { // Validate name if (empty($_POST["name"])) { $nameErr = "Name is required"; } else { $name = test_input($_POST["name"]); // Check if name contains only letters and whitespace if (!preg_match("/^[a-zA-Z ]*$/", $name)) { $nameErr = "Only letters and white space allowed"; } } // Validate email if (empty($_POST["email"])) { $emailErr = "Email is required"; } else { $email = test_input($_POST["email"]); // Check if email address is valid if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { $emailErr = "Invalid email format"; } } // Validate message if (empty($_POST["message"])) { $messageErr = "Message is required"; } else { $message = test_input($_POST["message"]); } // Check if form is valid if (empty($nameErr) && empty($emailErr) && empty($messageErr)) { $formSubmitted = true; // In real implementation, you would send email or save to database here } } // Function to sanitize input data function test_input($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data; } ?>