PHP Cheatsheet — Quick Reference
A concise quick-reference for PHP 8.3 syntax, types, arrays and the most-used standard library — covers ~80% of everyday needs.
PHP PHP 8.3 (LTS-style)
Zend Engine (PHP runtime) · Imperative, OO, functional · Dynamic (with optional static types)
Recommended Learning Path
First get comfortable running `php hello.php` and the built-in `php -S` server → master variables, types and control flow → go deeper into functions, closures and arrays → understand reference semantics and object handles → organize code with classes, interfaces and exceptions → then on-demand learn file I/O, cURL, time and regex → handle concurrency with Fiber/pcntl. The FAQ section is great for a second pass to avoid pitfalls.
1.Hello World & Runtime
Running PHP programs, the built-in web server, command-line arguments, and exit codes.
Minimal program
A PHP file starts with <?php; run with `php filename` on the CLI. `echo` prints strings.
CLI run
The `php` command runs scripts directly. `php -l` checks syntax; `php -r` executes a one-liner.
Built-in web server
`php -S` starts the built-in server using a directory as the doc root — great for local dev.
File structure
`<?php` and `?>` tags split PHP from HTML. Pure-PHP files should omit the closing tag.
Command-line arguments
`$argv` is the arguments array; `$argc` is the count; `$argv[0]` is the script name.
Exit codes
`exit()` or `die()` ends the script and returns a status code: 0 for success, non-zero for failure.
File inclusion
`require` pulls in a file that must exist; `include` only warns on failure; `_once` prevents double inclusion.
Environment check
`php -i` dumps config; `php -m` lists extensions; `phpinfo()` outputs the full report.
2.Variables & Constants
Variable declarations, constants, type declarations, strict mode, and scope.
Variable declaration
Variables start with `$`; no type declaration needed, created on first assignment; names are case-sensitive.
Value-copy assignment
Plain assignment copies by value; scalars are independent. Arrays are also copied but with copy-on-write underneath.
Constants
`const` defines namespaced constants; `define()` defines global ones; immutable after creation.
Magic constants
`__DIR__`, `__FILE__`, `__LINE__` etc. resolve at compile-time — handy in log output.
Scope & static
Variables inside functions are local by default; `global` exposes globals; `static` persists across calls.
Parameter & return types
Parameters and returns can be type-declared; weak mode auto-coerces, `strict_types` makes it strict.
Strict mode
`declare(strict_types=1)` strictly checks types and throws `TypeError` on mismatch.
Naming conventions
Classes & namespaces UpperCamelCase; functions & variables camelCase; constants UPPER_CASE; PSR-12.
3.Data Types
Scalars, arrays, null, enums, and the type system, plus how to think about loose conversion and type checking.
Scalar types
`int`, `float`, `string`, `bool` are the four scalars. Strings are byte sequences; Chinese is multibyte.
Arrays
A PHP array is an ordered map with int and string keys — it doubles as a list and a dict.
null & empty values
`null` means no value. Unset variables, explicit `null`, and `null` returns are all `null`.
callable & iterable
`callable` is anything invokable; `iterable` is any array or `Traversable` object.
mixed & void
`mixed` is any type; `void` is no return; `never` means never returns.
enum
`enum` (8.1+) defines a set of named cases — pure or backed, with optional methods.
Union & intersection types
`int|float` accepts either; intersection types must satisfy multiple interface constraints at once.
Weak type coercion
In weak mode operations auto-coerce types; string/number comparisons have special rules — see FAQ.
Type-check functions
`is_int`, `is_string`, and the rest of the `is_*` family check types and return booleans.
4.References & Memory Semantics
PHP has no raw pointers: variable references, copy-on-write, object handles, and null handling.
What a reference is
A PHP reference is an alias for a variable — both names point to the same content and update together.
Copy-on-write
Arrays and objects share data on assignment; the copy happens only when you write, saving memory.
Reference assignment
`unset` only breaks the binding for that name — the underlying value still lives through other aliases.
Reference parameters
Prefix a parameter with `&` to pass by reference — changes inside the function affect the caller's variable.
Object handles
An object variable holds a handle — assignment and pass-by-value still point to the same instance; use `clone` for a copy.
null handling
`isset` checks present and not `null`; `is_null` checks for `null`; `empty` checks for empty.
Null coalescing ??
`??` returns the right side if the left is missing or `null` — chainable and pairs with `throw`.
Variable variables
`$$var` uses a variable's value as another variable's name — poor readability; prefer arrays.
unset & memory
`unset` drops a name and decrements the refcount; the GC handles remaining cyclic references.
5.Control Flow
Conditionals, loops, switch, match, and break/continue.
if / else
`if` evaluates a condition; `elseif` tries the next; `else` is the fallback.
Ternary operator
Condition `?` then `:` else is an expression you can assign; nesting hurts readability.
switch statement
`switch` uses loose comparison by default; remember `break` to avoid fall-through; `default` is the catch-all.
match expression
`match` (8.0+) compares strictly, returns a value, no `break` needed.
for loop
`for(init; cond; step)` is the classic counted loop — the step is fully under your control.
foreach iteration
`foreach` iterates arrays and objects, fetching key and value; watch out for reference-residue bugs.
while & do-while
`while` checks first and may run zero times; `do-while` runs at least once.
break & continue
`break` exits the loop or switch; `continue` skips to the next iteration; pass a count to jump multiple levels.
6.Functions & Closures
Function definitions, default parameters, variadic parameters, named arguments, closures, and generators.
Function definition
`function` defines a function with typed params and a `return`. Function names are case-insensitive.
Default parameters
Parameters can take default values that may be omitted at call time; defaults must be constant expressions.
Variadic parameters
`...$args` collects the remaining arguments into an array; it must be last in the parameter list.
Named arguments
Pass args as `name: value` (8.0+) to skip optional ones and order them freely.
Return types
The return type comes after the colon: `void`, nullable `?T`, union types and `array` are supported.
Closures
Anonymous functions use `function()`; `use` captures outer variables; assign them or pass as callbacks.
Arrow functions
`fn() => expr` auto-captures outer variables by value — concise single-expression callbacks.
First-class callables
8.1+ syntax `strlen(...)` creates a first-class callable, making functions first-class values.
Generators
Functions that `yield` values are generators — lazy by nature, ideal for memory-efficient large data.
7.Strings
String literals, interpolation, concatenation, multibyte handling, and the functions you reach for most.
String literals
Single quotes output literally; double quotes interpret escapes and variables. Both styles are common.
Variable interpolation
Inside double quotes `$var` interpolates; complex expressions need braces like `{$arr['k']}`.
String concatenation
`.` concatenates two strings; `.=` appends. For many joins, `implode` or `sprintf` is clearer.
Multibyte functions
For Chinese text use the `mb_*` family — they count characters while `strlen` counts bytes.
Formatting sprintf
`sprintf`/`printf` use `%s`, `%d` placeholders — much more readable than concatenation.
Search & replace
`strpos` finds a position; `str_contains` tests inclusion; `str_replace` does bulk replacement.
Split & join
`explode` splits a string by a delimiter into an array; `implode` joins an array back.
Case & trim
`strtolower`/`strtoupper` change case; `trim` strips whitespace at both ends; `ltrim`/`rtrim` do one side.
8.Arrays & Collections
Creating arrays, adding, removing, updating and looking up elements, iteration, sorting, and Spl data structures.
Creating arrays
Use `[]` or `array()` to create arrays. Literals auto-assign increasing integer keys.
Access & modify
Subscript notation accesses elements; `[]` appends; `unset` deletes. Reading a missing key warns.
Push, pop & count
`array_push`/`array_pop` work the tail; `array_shift`/`unshift` work the head; `count` returns the size.
Iterating arrays
`foreach` walks values or key/value pairs; list destructuring works for 2D arrays.
Map & filter
`array_map` transforms each element; `array_filter` keeps those that match; `array_reduce` folds.
Sorting
`sort` sorts values, `ksort` by key, `asort` by value while preserving keys, `usort` uses a custom comparator.
Merge & slice
`array_merge` joins arrays, `array_slice` extracts a sub-array, `array_combine` zips keys and values.
Destructuring assignment
List `[]` or keyed `[]` destructuring assigns array elements to multiple variables — also in `foreach`.
Spl data structures
`SplStack`, `SplQueue`, `SplFixedArray` provide fixed-purpose data structures.
9.Memory & Performance
Reference counting, the cyclic-reference GC, WeakReference, and measuring memory.
Reference counting
`zval` tracks a refcount; when it hits zero the memory is reclaimed immediately. Assignments and calls increment it.
Cyclic-reference GC
When objects reference each other, refcounts never reach zero — the cyclic GC reclaims them periodically.
WeakReference
`WeakReference` (8.0+) holds an object without preventing collection — great for caches.
Memory measurement
`memory_get_usage` reports current usage; `memory_get_peak_usage` reports the peak.
Timely release
`unset` large variables when done so refcounts drop, keeping peaks low and batches steady.
OPcache
OPcache caches compiled bytecode, avoiding recompilation per request — always on in production.
Large-data processing
Huge arrays eat memory — use generators, streaming reads, and `SplFixedArray` to keep usage flat.
Performance tips
Avoid concatenation-in-loops, pre-allocate, reuse connections, and cut redundant queries.
10.Object-Oriented
Classes, constructors, visibility, inheritance, interfaces, traits, and readonly properties.
Class definition
`class` defines a class with typed properties and methods. `new` creates instances.
Constructor & property promotion
`__construct` initializes the object. 8.0+ promotes constructor parameters directly to properties.
Visibility
`public` is open, `protected` is subclass-visible, `private` is class-only — default is `public`.
Inheritance
`extends` inherits from the parent; override methods; `parent::` calls the parent version.
Interfaces
`interface` defines method signatures; `implements` fulfils them. A class can implement many.
Abstract classes
`abstract class` cannot be instantiated; abstract methods must be implemented by subclasses.
trait reuse
`trait` is horizontal reuse across classes; `use` brings it in; you can combine several traits.
Static members
`static` properties and methods belong to the class, not instances; access via `self::` or `ClassName::`.
readonly properties
`readonly` properties (8.1+) can be assigned only at declaration or in the constructor — read-only afterwards.
11.Error Handling
The exception hierarchy, try/catch/finally, custom exceptions, and error handling.
try / catch
Exceptions thrown in `try` are caught by `catch` — execution continues after the catch block.
Throwable hierarchy
`Throwable` is the base; `Error` is engine-level; `Exception` is application-level.
Custom exceptions
Extend `Exception` or `RuntimeException` to define business exceptions with extra fields.
Multiple catch
Separate multiple exception types in `catch` with `|`; order matters — subclass before parent.
finally
`finally` runs whether or not an exception is thrown — perfect for resource cleanup.
Global exception handler
`set_exception_handler` is the catch-all for uncaught exceptions — central logging and response.
Error vs Exception
Engine errors are `Error` (types/args); application problems are `Exception` — catch them separately.
Exception chaining
When throwing a new exception from `catch`, pass the original as the third argument; `getPrevious` walks the chain.
12.File I/O
Reading and writing files, JSON, CSV, and the standard streams.
Reading files
`file_get_contents` reads an entire file into a string — first choice for small files; returns `false` on failure.
Writing files
`file_put_contents` writes a string; pass `FILE_APPEND` to append; it returns the bytes written.
Line-by-line reading
`fopen` + `fgets` read line by line with constant memory — ideal for large files.
Open modes
`fopen` modes `r`/`w`/`a` control read/write; `w` truncates the existing file.
JSON encode/decode
`json_encode` makes JSON; `json_decode` parses it. Pass `true` as the second argument to get arrays.
CSV read/write
`fgetcsv` parses a CSV row; `fputcsv` writes one — quoting and escaping are handled for you.
Directories & glob
`glob` matches files by pattern; `scandir` lists a directory; `mkdir` creates one.
Standard streams
`STDIN`, `STDOUT`, `STDERR` are constants for the standard streams — common in CLI scripts.
13.Common Pitfalls
The pitfalls you are most likely to hit in everyday development, and how to write it correctly.
== vs ===
`==` is loose (coerces); `===` is strict (type + value). Prefer `===` for comparisons.
foreach reference pitfall
After `foreach` modifies with `&`, the last element still aliases the array — reusing `$item` will pollute it.
isset & key existence
`isset` treats a key whose value is `null` as missing; `array_key_exists` reports true existence.
Weak-comparison pitfall
Weak comparisons have surprising string/number rules — `'0' == false` is true; convert explicitly.
Undefined-key warning
Reading a missing array key triggers a warning (8.0+); use `??` or `isset` first.
Output before header()
Once output has been sent, `header()` fails — either send headers first or use output buffering.
empty vs isset
`empty` is true for `0`, `''`, `'0'`, …; `isset` only cares about `null` — pick the one that fits your meaning.
SQL injection prevention
String-concatenated SQL invites injection — use PDO prepared statements with bound parameters.
14.Concurrency & Coroutines
PHP's concurrency models: multiple processes, coroutines, Fiber, and third-party extensions.
Process model
PHP is single-threaded by default; each request runs in its own process and variables die with it.
pcntl_fork multi-process
`pcntl_fork` spawns a child process; both run independently — CLI only.
Signal handling
`pcntl_signal` registers a handler; `dispatch` flushes pending signals.
parallel extension
`parallel` is a PECL extension providing real multithreaded workers — not built in.
Swoole coroutines
Swoole is a high-performance network framework with coroutine scheduling and resident memory — great for high concurrency.
Fiber coroutines
Fiber (8.1+) is the native coroutine: `suspend` to pause, `resume` to continue — manually scheduled.
Async libraries
No built-in `async`/`await` — use event-loop libraries like ReactPHP or Amp for async I/O.
Inter-process communication
Share data across processes via message queues, files, or shared memory — avoid concurrent edits to the same file.
15.Networking
HTTP clients, curl, URL parsing, sessions, and sockets.
HTTP requests
`file_get_contents` sends simple requests; pair it with `stream_context_create` for timeouts and headers.
curl extension
`curl_init` + `curl_exec` give you full request control, status codes, and error info.
POST & Guzzle
`stream_context` can POST JSON, but in real projects prefer the Guzzle HTTP client.
Request & response headers
`header()` sends response headers; `http_response_code` sets the status — both must run before output.
URL parsing
`parse_url` splits URL parts; `parse_str` parses query strings; `http_build_query` builds them.
Cookies & sessions
`session_start` starts a session; `setcookie` writes cookies; read from `$_COOKIE`.
Sockets
`stream_socket_client` connects to a remote host; `fwrite` sends and `fgets` reads.
SSE & WebSocket
SSE is one-way text streaming; WebSocket is bidirectional — choose by need.
16.Date & Time
Timestamps, formatting, parsing, time zones, and date arithmetic.
Getting current time
`time()` returns the Unix timestamp in seconds; `microtime(true)` adds millisecond precision; `date` formats it.
Formatting dates
`date()` renders a timestamp with format specifiers — year, month, day, time and locale-friendly variants.
Parsing dates
`strtotime` parses date strings and relative phrases; returns `false` on failure.
Timestamps
A Unix timestamp is UTC seconds; `DateTime` converts between timestamps and objects.
Time zones
`date_default_timezone_set` sets the default zone; a `DateTime` can carry its own zone.
Intervals
`DateInterval` represents a duration; `DateTime::add`/`sub` shifts a date by one.
Date diff
`DateTime::diff` returns a `DateInterval` — useful for ages, days remaining, etc.
Sleep & timers
`sleep` blocks; event-loop timers schedule delayed tasks without blocking.
17.Processes & CLI
Command-line arguments, input and output, environment variables, and process control.
Command-line arguments
`$argv` holds command-line arguments; `$argv[0]` is the script name.
Reading input
`fgets(STDIN)` reads one line; `stream_get_contents` reads everything; `trim` strips the newline.
Running external commands
`shell_exec` captures output; `exec` returns the status code; use `escapeshellarg` to escape arguments.
Environment variables
`getenv` reads env vars; `putenv` sets them — sensitive config belongs in env vars.
Process info
`getmypid` returns the current PID; the `posix_*` family checks user / parent; `hrtime` measures time.
Process signals
`pcntl_signal` controls signal handling; `pcntl_wait` waits for child exit.
Pipes & terminal
`stream_isatty` detects an interactive terminal; `STDERR` shows progress; `exit` sets the code.
Exit codes
`exit()` takes a status code: 0 for success, non-zero for failure; shell reads it via `$?`.
18.Regular Expressions
Matching, capturing, replacing, splitting, and multibyte patterns.
preg_match
`preg_match` finds the first match; capture groups land in `$m`; named groups by name.
preg_match_all
`preg_match_all` finds every match — default grouping is per-group; `PREG_SET_ORDER` groups per match.
preg_replace
`preg_replace` replaces via regex with `$1`-style backrefs; `preg_replace_callback` uses a callback.
Common patterns
Character classes, quantifiers and greediness — plus delimiters and escaping rules.
Captures & assertions
Capture groups, non-capturing groups, named groups, and lookaround assertions.
Anchors & boundaries
`^` line start, `$` line end, `\b` word boundary, `m` modifier for multiline.
Regex split
`preg_split` splits by regex — it can keep delimiters and limit the number of pieces.
Multibyte & u modifier
Add the `u` modifier for Chinese text; `preg_quote` escapes user input.
19.Build & Toolchain
Composer dependency management, autoloading, and CLI build workflows.
Initializing a project
`composer init` generates `composer.json` with dependencies and autoload rules.
Installing dependencies
`composer install` installs from the lock file; `composer require` adds new dependencies.
Using dependencies
After `require vendor/autoload.php`, `use` any dependency class — autoloading just works.
PSR-4 autoloading
Namespaces map one-to-one to directories; `App\` → `src/` — run `dump-autoload` after edits.
Composer scripts
`composer.json`'s `scripts` define command shortcuts and lifecycle hooks.
Version constraints
Constraints like `^`, `~`, `>=` control version ranges; the lock file pins exact versions.
CLI publish commands
Framework commands (artisan / console) run migrations, cache tasks and scheduled jobs.
PHP configuration
`php -i` / `php --ini` / `php -m` inspect the runtime; `ini_get` reads a setting.
Official Links
Direct links to the official docs and resources.
About this Cheatsheet
This page is a self-contained quick reference for PHP 8.3 covering ~80% of common usage in real projects: the language core and the most-used standard library. It leans toward modern idioms — declare(strict_types=1), enum cases (8.1+), readonly properties, match expressions, named arguments, arrow functions, and first-class callables. For the authoritative reference, see the official PHP manual and PHP The Right Way. 19 sections each focus on a single theme — from your first program through arrays, object-oriented code, and common pitfalls. Each section is split into 8–14 bite-sized topics (5–20 lines of code each) for ~150 topics total. The snippets are deliberately short and self-explanatory. Everything runs in your browser — no uploads, no tracking. This page is part of GuruToolkit's free developer tools; the snippets here are free to use with no warranty.
Version 2.1.0