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);
<?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);
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";
}
<?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";
}
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");
<?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");
usort($adults, fn($a, $b) => $a["age"] <=> $b["age"]);
echo "Adults: " . implode(", ", $names) . "\n";
foreach ($adults as $u) {
echo " {$u['name']} โ {$u['age']}\n";
}
Class, readonly, encapsulation
<?php
class BankAccount {
private float $balance;
private array $log = [];
public function __construct(
public readonly string $owner,
float $initial = 0.0
) {
<?php
class BankAccount {
private float $balance;
private array $log = [];
public function __construct(
public readonly string $owner,
float $initial = 0.0
) {
$this->balance = $initial;
}
public function deposit(float $amt): void {
$this->balance += $amt;
$this->log[] = "+{$amt}";
}
public function withdraw(float $amt): bool {
if ($amt > $this->balance) return false;
$this->balance -= $amt;
$this->log[] = "-{$amt}";
return true;
}
public function summary(): string {
return "{$this->owner}: โน{$this->balance} | " . implode(", ", $this->log);
}
}
$acc = new BankAccount("Nishu", 1000.0);
$acc->deposit(500);
$acc->withdraw(200);
echo $acc->summary();
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
);
<?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
);
echo "Emails found:\n";
foreach ($matches[0] as $email) {
echo " โ $email\n";
}
$phones = ["9876543210", "123", "+91-98765"];
foreach ($phones as $p) {
$ok = preg_match('/^\d{10}$/', $p) ? "valid" : "invalid";
echo "$p โ $ok\n";
}
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,
<?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,
"ts" => time(),
], JSON_PRETTY_PRINT);
exit;
}
$users = [
["id" => 1, "name" => "Nishu", "role" => "admin"],
["id" => 2, "name" => "Alice", "role" => "user"],
];
apiResponse($users);
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"];
<?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"];
foreach ($attempts as $attempt) {
$ok = password_verify($attempt, $hash) ? "โ VALID" : "โ WRONG";
echo "\"$attempt\" โ $ok\n";
}
// Check if rehash needed
if (password_needs_rehash($hash, PASSWORD_BCRYPT, ["cost" => 14])) {
echo "\nRehash recommended for higher security";
}
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;
}
<?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;
}
public function create(string $name, string $email): int {
$stmt = $this->pdo->prepare(
"INSERT INTO users (name, email, created_at) VALUES (?, ?, NOW())"
);
$stmt->execute([$name, $email]);
return (int)$this->pdo->lastInsertId();
}
public function findAll(int $limit = 20): array {
$stmt = $this->pdo->prepare(
"SELECT id, name, email FROM users ORDER BY created_at DESC LIMIT ?"
);
$stmt->execute([$limit]);
return $stmt->fetchAll();
}
}
// $repo = new UserRepository($pdo);
// $user = $repo->findById(1);