PHP PHP 8.2+ / 8.3
PHP 8 Quick Reference
Essential modern PHP 8 syntax, associative arrays, match expressions, typed classes, JSON helpers, and security best practices.
declare(strict_types=1); match ($x) { ... }; fn($n) => $n * 2;
Core Syntax & Types
| Syntax | Purpose | Example |
|---|---|---|
declare(strict_types=1); | Enforce strict parameter & return types | Place at top of PHP files |
$var / "Hello $name" | Variables & double-quote interpolation | $title = "PHP 8"; |
?? | Null coalescing default | $user = $_GET['u'] ?? 'Guest'; |
match ($v) { ... } | Strict expression-based branching | match ($role) { 'admin' => 1, default => 0 } |
Arrays, Classes & Web Security
| API / Syntax | Purpose | Example |
|---|---|---|
foreach ($arr as $k => $v) | Loop keys and values | foreach ($tracks as $k => $v) |
array_filter / array_map | Functional array transforms | array_filter($xs, fn($n) => $n >= 80) |
public readonly string $x | Constructor property promotion | Inside public function __construct(...) |
htmlspecialchars() | Escape untrusted output (prevent XSS) | htmlspecialchars($s, ENT_QUOTES, 'UTF-8') |
$pdo->prepare(...) | Prevent SQL injection with bound params | $stmt->execute([$email]); |
json_encode / json_decode | JSON API serialization | json_encode($data, JSON_THROW_ON_ERROR) |