PHP code snippets with use cases
30 ready-made code building blocks, sorted by topic.
Basics
- Hello World β A first test of whether PHP is installed correctly and runs.
- Variables and Types β Store values and check their type with gettype/var_dump.
- Null Coalescing and Nullsafe β Handle missing form values or optional configuration with default values.
- Date and Time with DateTimeImmutable β Calculate deadlines, format timestamps, count days until an event.
Control flow
- if / elseif / else β React differently, e.g. for grades, price tiers or permissions.
- for and foreach Loop β Process every element of an array or repeat n times.
- match Instead of switch β Translate values into texts, prices or actions, e.g. HTTP status codes or roles.
Data structures
- Working with Arrays as a List β Manage collections of values: add, sort, filter, convert.
- Associative Array (Map) β Store mappings, e.g. configurations, database rows or JSON-like data.
- Sorting with usort and <=> β Order records by a field, e.g. users by age or products by price.
- array_column and Grouping β Prepare database rows: extract a column, index by ID or group.
OOP
- Class with Inheritance β Bundle data and behavior, e.g. users, products or game characters.
- Enum with Method β Model fixed choice values (status, roles, payment methods) in a type-safe way instead ofβ¦
- Immutable Value Object β Transport data between layers (DTO) or model money/coordinates immutably.
Web
- Processing a Form (POST) β Receive and validate a contact form, registration or comment feature.
- Session and Login Protection β Recognize logged-in users and protect pages.
- HTTP Request with cURL β Fetch data from an external web API, e.g. weather, GitHub or payment services.
Security
- Preventing XSS with htmlspecialchars β Output user comments, names or search terms into HTML safely.
- Hashing and Verifying Passwords β Registration and login: never store passwords in plain text.
- CSRF Token for Forms β Prevent foreign websites from triggering actions (delete, pay) on your behalf.
More snippets
- Function with Types and Named Argument β Bundle recurring logic, e.g. greeting texts, price calculation, formatting.
- Named Arguments and Spread β Call functions with many optional parameters readably, e.g. for configuration objects.
- try / catch / finally β Catch faulty calculations or input without the script aborting.
- Write and Read a File β Save logs, configurations or text data and load them again.
- Handling JSON β Exchange data with web APIs and JavaScript, read configuration files.
- String Functions and Formatting β Check, transform and format texts for display (prices, slugs).
- Regular Expression (preg) β Find and replace email addresses, phone numbers or patterns in text.
- PDO: Querying Data β Read rows from MySQL/SQLite safely, e.g. look up users or display product lists.
- PDO: Transaction β Execute related changes atomically, e.g. bank transfers or orders with stock levels.
- Generator for Large Data β Process large files or database results without holding everything in memory.