Examples
PHP 8.3.8

๐Ÿ’ก Code Examples

Real-world PHP โ€” copy or study each pattern

Hello World
Basics
Variables, echo, string interpolation
<?php
$name = "World";
echo "Hello, $name!\n";
echo "PHP " . PHP_VERSION . " running on " . PHP_OS . "\n";
$pi = M_PI;
printf("Pi is approximately %.4f\n", $pi);
FizzBuzz
Basics
Classic loop with conditionals
<?php
for ($i = 1; $i <= 20; $i++) {
    echo match(true) {
        $i % 15 === 0 => "FizzBuzz",
        $i % 3  === 0 => "Fizz",
        $i % 5  === 0 => "Buzz",
        default        => (string)$i,
    } . "\n";
}
Array Operations
Basics
filter, map, reduce, sort
<?php
$users = [
    ["name" => "Alice", "age" => 28],
    ["name" => "Bob",   "age" => 16],
    ["name" => "Carol", "age" => 34],
];

$adults = array_filter($users, fn($u) => $u["age"] >= 18);
$names  = array_column(array_values($adults), "name");
OOP Bank Account
Intermediate
Class, readonly, encapsulation
<?php
class BankAccount {
    private float $balance;
    private array $log = [];

    public function __construct(
        public readonly string $owner,
        float $initial = 0.0
    ) {
Regex Email Finder
Intermediate
preg_match_all, validation
<?php
$text = "Contact info@example.com or support@phpforge.dev for help.";

preg_match_all(
    '/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/',
    $text,
    $matches
);
JSON API Response
Intermediate
REST response pattern
<?php
header("Content-Type: application/json");

function apiResponse(array $data, int $code = 200, string $msg = "OK"): void {
    http_response_code($code);
    echo json_encode([
        "status"  => $code,
        "message" => $msg,
        "data"    => $data,
Password Hashing
Advanced
Secure bcrypt with verify
<?php
$password = "MySecret@123";

// Hash with bcrypt cost 12
$hash = password_hash($password, PASSWORD_BCRYPT, ["cost" => 12]);
echo "Hash: $hash\n\n";

// Verify
$attempts = [$password, "WrongPass", "MySecret@123"];
PDO Repository Pattern
Advanced
Prepared statements, CRUD
<?php
class UserRepository {
    public function __construct(private PDO $pdo) {}

    public function findById(int $id): ?array {
        $stmt = $this->pdo->prepare("SELECT * FROM users WHERE id = ?");
        $stmt->execute([$id]);
        return $stmt->fetch() ?: null;
    }