📡 You're offline — showing cached content
New version available!
Quick Access
PHP Reference

PHP 8 Reference

Array functions, string methods, and new features.

All Topics

PHP 8 Core Syntax

match expression
Strict type match (===). Returns a value. No fallthrough. Throws UnhandledMatchError if no arm matches.
Example: $label = match($code) { 200 => 'OK', 404 => 'Not Found', default => 'Unknown' };
Named arguments
Pass args by name in any order — great for functions with many optional params.
Example: array_slice(array: $arr, offset: 2, length: 5, preserve_keys: true);
Nullsafe operator (?->)
Short-circuit chain — returns null if any method in chain returns null instead of throwing.
Example: $city = $user?->getAddress()?->getCity()?->getName();
Union types (int|string)
Function params and return types can accept multiple types. PHP 8.1 adds intersection types (A&B).
Example: function process(int|string $id): User|null { ... }
Fibers (8.1)
Cooperative concurrency primitive — pause execution at any point and resume later.
Example: $fiber = new Fiber(function() { $val = Fiber::suspend('first'); echo $val; }); $fiber->start(); $fiber->resume('second');
Enums (8.1)
First-class enums — backed by string/int, implement interfaces, have methods and constants.
Example: enum Status: string { case Active = 'active'; case Pending = 'pending'; public function label(): string { return ucfirst($this->value); } }
Readonly properties (8.1)
Can only be initialized once — enforces immutability without extra boilerplate.
Example: class User { public function __construct(public readonly int $id, public readonly string $email) {} }
First class callables (8.1)
Create closures from any callable using ... syntax — cleaner than Closure::fromCallable.
Example: $fn = strlen(...); $sorted = usort($arr, strcmp(...));

Arrays & Strings

array_map / array_filter
array_map with null callback zips multiple arrays. array_filter with no callback removes falsy values.
Example: $names = array_map(fn($u) => $u->name, $users); $active = array_filter($users, fn($u) => $u->active);
array_reduce
Fold array to single value with accumulator. Works like JS .reduce().
Example: $total = array_reduce($items, fn($carry, $item) => $carry + $item->price, 0);
array_column
Extract a single column from an array of arrays/objects. Also re-index by column value.
Example: $emails = array_column($users, 'email'); $byId = array_column($users, null, 'id');
usort / uasort / uksort
Sort by custom callback preserving (a)ssociative keys / (k)ey sort.
Example: usort($posts, fn($a, $b) => $b->views <=> $a->views);
array_unique / array_diff
Remove duplicates / values present in first array but not others. array_intersect for common values.
Example: $new = array_diff($all, $existing); $common = array_intersect($a, $b);
str_contains / str_starts_with
PHP 8.0 string helpers — cleaner than strpos() !== false or substr() comparisons.
Example: if (str_starts_with($url, 'https') && str_contains($body, 'error')) { ... }
sprintf / number_format
Format strings with placeholders. number_format for localized decimal/thousand separator.
Example: sprintf("%.2f", $price); number_format(1234567.89, 2, '.', ',')
preg_match / preg_replace / preg_split
Full PCRE regex. preg_match_all for all matches. preg_replace_callback for transform on match.
Example: preg_match('/^(\d{4})-(\d{2})-(\d{2})$/', $date, $m); $m[1]; $m[2]; $m[3];

OOP & Design Patterns

Constructor promotion
Declare and initialize class properties in constructor signature — reduces boilerplate.
Example: class Product { public function __construct(private string $name, private float $price) {} }
Interface / Abstract class
Interface: contract (no implementation). Abstract: partial implementation with enforced methods.
Example: interface Cacheable { public function getCacheKey(): string; public function ttl(): int; }
Traits
Reusable method groups for horizontal code sharing across unrelated class hierarchies.
Example: trait Timestampable { public function touch(): void { $this->updated_at = new DateTime(); } }
Late static binding (static::)
static:: refers to the class that was called at runtime (not where method was defined). Enables correct inheritance.
Example: class Base { public static function create(): static { return new static(); } }
__invoke / __toString
Make objects callable like functions / convert object to string automatically.
Example: class Multiplier { public function __invoke(int $n): int { return $n * $this->factor; } }
Repository pattern
Decouple data persistence from business logic — easily swap databases by changing one class.
Example: interface UserRepo { public function findById(int $id): ?User; public function save(User $u): void; }
Dependency Injection
Pass dependencies as constructor args instead of creating inside — testable, swappable, SOLID.
Example: class OrderService { public function __construct(private OrderRepo $orders, private Mailer $mail) {} }

Security & Best Practices

password_hash / verify
bcrypt by default (PASSWORD_DEFAULT). Never use md5/sha1 for passwords. Auto-detects if rehash needed.
Example: $hash = password_hash($pass, PASSWORD_ARGON2ID); password_verify($input, $hash);
htmlspecialchars
Escape output to prevent XSS. Always use ENT_QUOTES | ENT_HTML5 and specify charset.
Example: echo htmlspecialchars($user_input, ENT_QUOTES | ENT_HTML5, 'UTF-8');
PDO prepared statements
The ONLY correct way to run parameterized queries — prevents SQL injection completely.
Example: $stmt = $pdo->prepare("SELECT * FROM users WHERE email = ?"); $stmt->execute([$email]);
csrf_token pattern
Generate random token in session, include in forms as hidden field, validate on POST.
Example: $_SESSION['csrf'] = bin2hex(random_bytes(32)); // verify: hash_equals($session_token, $post_token)
random_bytes / random_int
Cryptographically secure random data. Never use rand() or mt_rand() for security purposes.
Example: $token = bin2hex(random_bytes(32)); $code = random_int(100000, 999999);
hash_hmac
Keyed message authentication code — sign data with a secret key (API signatures, JWT).
Example: $sig = hash_hmac('sha256', $payload, $_ENV['SECRET_KEY']);
filter_var validation
Built-in validation and sanitization filters — FILTER_VALIDATE_EMAIL, FILTER_VALIDATE_URL, FILTER_SANITIZE_NUMBER_INT.
Example: if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { throw new \InvalidArgumentException('Bad email'); }
environment variables
Never hardcode secrets. Use $_ENV or getenv(). Load .env with vlucas/phpdotenv in dev.
Example: $key = $_ENV['DB_PASSWORD'] ?? throw new \RuntimeException('Missing DB_PASSWORD');

Error Handling & Modern I/O

set_exception_handler
Global uncaught exception handler — log, display safe error page, and exit gracefully.
Example: set_exception_handler(fn($e) => logAndRespond($e));
Throwable interface
Base interface for both Error and Exception — catch all failures with catch(Throwable $e).
Example: try { ... } catch (\Throwable $e) { logger()->critical($e->getMessage()); }
Generator::send()
Two-way communication with generators — yield receives value sent from outside.
Example: $gen = logger(); $gen->current(); $gen->send("message to log");
file_put_contents / file_get_contents
Simple file I/O. FILE_APPEND flag. file_get_contents also works for HTTP (slowww — use cURL instead).
Example: file_put_contents('app.log', $msg . PHP_EOL, FILE_APPEND | LOCK_EX);
SplFileObject / SplQueue
SPL data structures for typed, OO file and queue operations.
Example: $csv = new SplFileObject('data.csv'); $csv->setFlags(SplFileObject::READ_CSV); foreach($csv as $row) { ... }
DateTime / DateTimeImmutable
Use DateTimeImmutable — modifications return new object, no mutation bugs.
Example: $expires = (new DateTimeImmutable())->add(new DateInterval('P30D'));