📖 Guide

PHP — Complete Reference

Comprehensive PHP cheat sheet covering syntax, OOP, arrays, PDO, and modern PHP 8.x features.

121 commands across 11 categories

Basics

CommandDescription
<?php ... ?>
PHP opening and closing tags
$variable = value;
Declare a variable (no type keyword needed)
echo 'text';
Output a string to the browser/stdout
print_r($var);
Print human-readable info about a variable (arrays, objects)
var_dump($var);
Dump detailed type and value information
define('NAME', value);
Define a constant (global scope)
const NAME = value;
Define a class or namespace constant
// comment /* block */
Single-line and multi-line comments
(int) $var (string) $var
e.g. $num = (int) '42'; // 42
Type casting between types
gettype($var)
Get the type of a variable as a string
isset($var)
Check if variable is set and not null
empty($var)
Check if variable is empty (false, 0, '', null, [])

Strings

CommandDescription
strlen($str)
Get the length of a string
strtolower($str)
Convert string to lowercase
strtoupper($str)
Convert string to uppercase
substr($str, $start, $len)
e.g. substr('Hello', 1, 3) // 'ell'
Extract a substring
strpos($haystack, $needle)
Find position of first occurrence (false if not found)
str_replace($search, $replace, $str)
Replace all occurrences in a string
explode($delimiter, $str)
e.g. explode(',', 'a,b,c') // ['a','b','c']
Split string into array
implode($glue, $arr)
Join array elements into a string
trim($str)
Strip whitespace from beginning and end
sprintf($format, ...$args)
e.g. sprintf('Hello %s, age %d', 'Dan', 28)
Return a formatted string
"Hello {$name}"
Variable interpolation in double-quoted strings
str_contains($haystack, $needle)
Check if string contains substring (PHP 8.0+)

Arrays

CommandDescription
$arr = [1, 2, 3];
Create an indexed array
$arr = ['key' => 'val'];
Create an associative array
array_push($arr, $val)
Add element(s) to end of array
array_pop($arr)
Remove and return the last element
array_merge($a, $b)
Merge two or more arrays
array_keys($arr)
Return all keys of an array
array_values($arr)
Return all values (re-indexed)
in_array($needle, $arr)
Check if value exists in array
array_map($fn, $arr)
e.g. array_map(fn($x) => $x * 2, [1,2,3])
Apply callback to each element, return new array
array_filter($arr, $fn)
Filter array elements using a callback
sort($arr) / asort($arr)
Sort by value (sort reindexes, asort preserves keys)
array_slice($arr, $offset, $len)
Extract a slice of the array

Functions

CommandDescription
function name($param) { }
Declare a named function
function name($p = 'default')
Parameter with default value
function name(int $p): string
Type declarations for params and return
function name(): void
Function that returns nothing
fn($x) => $x * 2
Arrow function (single expression, auto-captures outer scope)
$fn = function($x) use ($y) { }
Anonymous function (closure) with captured variable
function name(string ...$args)
e.g. function sum(int ...$nums) { return array_sum($nums); }
Variadic function (accepts any number of args)
return $value;
Return a value from a function
function name(): ?string
Nullable return type (can return string or null)
function name(string|int $p)
Union type parameter (PHP 8.0+)

Classes & OOP

CommandDescription
class Name { }
Declare a class
new ClassName()
Instantiate an object
public / protected / private
Visibility modifiers for properties and methods
__construct()
Constructor method, called on instantiation
class Child extends Parent
Inheritance — extend a parent class
interface Name { }
Declare an interface (contract)
class X implements IFace
Implement an interface
abstract class Name { }
Abstract class — cannot be instantiated directly
trait Name { }
Declare a trait for horizontal code reuse
$this->prop self::CONST
Access instance property / class constant
public function __construct(private string $name)
Constructor promotion (PHP 8.0+) — declares and assigns in one step
enum Status: string { case Active = 'active'; }
Backed enum (PHP 8.1+)

Error Handling

CommandDescription
try { } catch (Exception $e) { }
Try-catch block for exception handling
throw new Exception('msg');
Throw an exception
finally { }
Block that always executes after try/catch
$e->getMessage()
Get exception message string
$e->getCode()
Get exception error code
catch (TypeError | ValueError $e)
Catch multiple exception types (PHP 8.0+)
set_error_handler($callback)
Set a custom error handler function
error_reporting(E_ALL)
Set which PHP errors are reported
trigger_error('msg', E_USER_WARNING)
Trigger a user-level error
class MyEx extends Exception { }
Create a custom exception class

File I/O

CommandDescription
file_get_contents($path)
Read entire file into a string
file_put_contents($path, $data)
Write string to file (creates or overwrites)
file_put_contents($path, $data, FILE_APPEND)
Append to a file
fopen($path, 'r')
Open file and return handle ('r' read, 'w' write, 'a' append)
fgets($handle)
Read one line from file handle
fwrite($handle, $data)
Write to an open file handle
fclose($handle)
Close an open file handle
file_exists($path)
Check if file or directory exists
is_file($path) / is_dir($path)
Check if path is a file or directory
unlink($path)
Delete a file
scandir($dir)
List files and directories in a path

Database (PDO)

CommandDescription
new PDO($dsn, $user, $pass)
e.g. new PDO('mysql:host=localhost;dbname=app', 'root', '')
Create a database connection
$pdo->query($sql)
Execute a simple query (no user input!)
$pdo->prepare($sql)
Prepare a statement with placeholders
$stmt->execute([$val])
Execute prepared statement with bound values
$stmt->fetch(PDO::FETCH_ASSOC)
Fetch one row as associative array
$stmt->fetchAll(PDO::FETCH_ASSOC)
Fetch all rows as array of assoc arrays
$stmt->rowCount()
Number of rows affected by last statement
$pdo->lastInsertId()
Get the ID of the last inserted row
$pdo->beginTransaction()
Start a transaction
$pdo->commit() / $pdo->rollBack()
Commit or roll back a transaction
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION)
Set PDO to throw exceptions on errors

Superglobals

CommandDescription
$_GET['key']
Access URL query string parameters
$_POST['key']
Access form POST data
$_REQUEST['key']
Access GET, POST, and COOKIE data combined
$_SERVER['REQUEST_METHOD']
Get HTTP method (GET, POST, etc.)
$_SERVER['HTTP_HOST']
Get the host header from the request
$_FILES['input']
Access uploaded file info (name, tmp_name, size, error)
$_SESSION['key'] = value;
Store data in session (call session_start() first)
$_COOKIE['key']
Access cookie values
$_ENV['key']
Access environment variables
$GLOBALS['var']
Access any global variable by name

Common Functions

CommandDescription
json_encode($data)
Convert value to JSON string
json_decode($str, true)
Decode JSON string (true = assoc array)
date('Y-m-d H:i:s')
Format current date/time
time()
Get current Unix timestamp
strtotime('next Monday')
Parse date/time string to timestamp
intval($str) / floatval($str)
Convert string to int or float
number_format($num, 2)
Format number with decimals and separators
rand($min, $max)
Generate a random integer in range
password_hash($pw, PASSWORD_DEFAULT)
Securely hash a password
password_verify($pw, $hash)
Verify a password against its hash
header('Location: /page')
Send HTTP header (redirect, content-type, etc.)

Modern PHP (8.x)

CommandDescription
$result = $val?->method()
Nullsafe operator — short-circuits to null if $val is null
$x = $a ?? 'default';
Null coalescing — use right side if left is null
match($val) { 1 => 'one', default => '?' }
Match expression — strict comparison, returns value
#[Attribute]
PHP 8.0 attributes (annotations)
str_starts_with($str, $prefix)
Check if string starts with substring (8.0+)
str_ends_with($str, $suffix)
Check if string ends with substring (8.0+)
readonly class Dto { }
Readonly class — all properties are readonly (8.2+)
enum Suit { case Hearts; case Spades; }
Pure enum declaration (8.1+)
$arr = [...$a, ...$b];
Spread operator in arrays
function f(mixed $val): never
never return type — function always throws or exits (8.1+)

More Guides

🌿
Git Commands
Complete Git command reference — from basics to advanced workflows. Searchable, with examples.
📝
Vim Commands
Complete Vim/Vi command reference — modes, motions, editing, search, and advanced features.
🐳
Docker Commands
Complete Docker & Docker Compose command reference — containers, images, volumes, networks, and orchestration.
🔤
Regex Reference
Complete regular expression reference — syntax, patterns, quantifiers, groups, lookaheads, and common recipes.
🐧
Linux Commands
Complete Linux/Bash command reference — file management, text processing, networking, system admin, and shell scripting.
☸️
Kubernetes Commands
Complete Kubernetes & kubectl command reference — pods, deployments, services, configmaps, and cluster management.
🐍
Python Reference
Complete Python reference — syntax, data structures, string methods, file I/O, comprehensions, and common patterns.
🗃️
SQL Reference
Complete SQL reference — queries, joins, aggregation, subqueries, indexes, and database management.
🌐
Nginx Reference
Complete Nginx configuration reference — server blocks, locations, proxying, SSL, load balancing, and caching.
🔐
SSH Commands
Complete SSH reference — connections, key management, tunneling, config, SCP/SFTP, and security hardening.
👷
Jenkins Reference
Complete Jenkins reference — pipeline syntax, Jenkinsfile, plugins, CLI, agents, and CI/CD patterns.
📨
HTTP Headers Reference
Complete HTTP headers reference — request headers, response headers, caching, security, CORS, and content negotiation. Searchable, with examples.
🐘
PostgreSQL Reference
Comprehensive PostgreSQL reference — from connection basics to advanced features like JSONB, full-text search, window functions, and performance tuning.
Async Patterns Reference
Multi-language async/concurrency patterns — JavaScript, Python, Go, Rust, Java, and universal concurrency patterns.
📡
Protobuf & gRPC Reference
Comprehensive reference for Protocol Buffers (proto3) and gRPC — message definitions, services, streaming, and common patterns.
📚
JS Array Methods
Complete JavaScript Array methods reference — creating, searching, transforming, sorting, iterating, and common patterns. Searchable, with examples.
🌊
Tailwind CSS Reference
Complete Tailwind CSS reference — layout, spacing, typography, colors, responsive design, states, and common patterns. Searchable, with examples.
GraphQL Reference
Complete GraphQL reference — schema definition, types, queries, mutations, directives, fragments, and common patterns. Searchable, with examples.
💻
VS Code Shortcuts
Complete VS Code keyboard shortcuts — editing, navigation, search, multi-cursor, terminal, debug, and more. Searchable, with Cmd/Ctrl notation.
🔲
CSS Grid Reference
Complete CSS Grid reference — container properties, item placement, grid functions, and common layout patterns. Searchable, with examples.
📦
CSS Flexbox Reference
Complete CSS Flexbox reference — container properties, item properties, and common layout patterns. Searchable, with examples.
⚛️
React Hooks Reference
Complete React Hooks reference — useState, useEffect, useContext, custom hooks, and common patterns. Searchable, with examples.
🔷
TypeScript Reference
Complete TypeScript reference — types, interfaces, generics, utility types, and advanced patterns. Searchable, with examples.
☁️
AWS CLI Reference
Complete AWS CLI reference — EC2, S3, IAM, Lambda, ECS, RDS, CloudFormation, and common operations.
🐹
Go Reference
Complete Go (Golang) reference — syntax, types, functions, concurrency, error handling, and common patterns.
💠
PowerShell Reference
Complete PowerShell reference — cmdlets, pipelines, scripting, file operations, remote management, and Active Directory.
💾
Redis Commands
Complete Redis command reference — strings, hashes, lists, sets, sorted sets, pub/sub, transactions, and server management.
🏗️
Terraform Commands
Complete Terraform reference — init, plan, apply, state management, modules, workspaces, and HCL syntax.
⚙️
Ansible Commands
Complete Ansible reference — playbooks, modules, inventory, roles, vault, and ad-hoc commands.
🟨
JavaScript
Complete JavaScript reference — variables, types, operators, strings, arrays, objects, functions, async, DOM, ES6+, and more.
🎨
CSS
Complete CSS reference — selectors, box model, positioning, typography, animations, media queries, custom properties, and more.
📄
HTML
Complete HTML reference — document structure, text content, forms, media, semantic elements, accessibility, and more.
Java
Complete Java reference — data types, strings, collections, OOP, interfaces, exceptions, file I/O, streams, lambdas, and more.
💻
Bash
Complete Bash reference — variables, strings, arrays, conditionals, loops, functions, file tests, I/O redirection, process management, and more.
🦀
Rust
Comprehensive Rust language cheat sheet covering ownership, traits, pattern matching, concurrency, and more.
📝
Markdown
Complete Markdown syntax reference for headings, formatting, links, tables, code blocks, and extensions.
📋
YAML
YAML syntax reference covering scalars, collections, anchors, multi-line strings, and common patterns.
🌐
Curl
Curl command-line reference for HTTP requests, authentication, file transfers, debugging, and common API patterns.
Cron
Cron scheduling reference covering syntax, field values, crontab management, and common schedule patterns.
🖥️
Tmux
Terminal multiplexer for managing multiple sessions, windows, and panes from a single terminal.
🔧
Awk
Powerful text processing language for pattern scanning, data extraction, and report generation.
✂️
Sed
Stream editor for filtering and transforming text, line by line.
🔍
Find
Search for files and directories in a directory hierarchy with powerful filtering options.
🔎
Grep
Search text using patterns. Filter lines from files, command output, or streams with regular expressions.
⚙️
C
Complete C programming cheat sheet covering syntax, pointers, memory management, and standard library.
🔷
C++
Complete C++ cheat sheet covering STL containers, OOP, templates, smart pointers, and modern C++ features.
🐬
MySQL
Complete MySQL cheat sheet covering queries, joins, indexes, transactions, and administration.
💅
Sass
Complete Sass/SCSS cheat sheet covering variables, mixins, functions, nesting, and modern module system.
🔐
Chmod
Linux file permission commands and patterns for chmod.
🔢
NumPy
Essential NumPy commands for array manipulation and numerical computing in Python.
🐼
Pandas
Pandas cheat sheet for data manipulation, analysis, and transformation in Python.
🎯
Dart
Dart language cheat sheet covering syntax, types, OOP, null safety, and async patterns.
🔺
Laravel
Laravel PHP framework cheat sheet for routing, Eloquent, Blade, Artisan, and more.
🟩
Node.js
Comprehensive Node.js runtime reference covering modules, file system, HTTP, streams, and more.
Next.js
Next.js App Router reference covering routing, data fetching, server components, and deployment.
🍃
MongoDB
MongoDB reference covering CRUD operations, aggregation, indexes, and administration.
🔥
Firebase
Firebase reference covering Authentication, Firestore, Realtime Database, Cloud Functions, and Hosting.
🐳
Docker Compose
Docker Compose reference covering CLI commands, service configuration, networking, volumes, and more.
💲
jQuery
Quick reference for jQuery selectors, DOM manipulation, events, AJAX, and more.
📐
LaTeX
Quick reference for LaTeX document structure, math mode, formatting, and common packages.
🎯
XPath
Quick reference for XPath expressions, axes, predicates, and functions for XML/HTML querying.
Emmet
Quick reference for Emmet abbreviations for lightning-fast HTML and CSS coding.
📦
TOML
Quick reference for TOML configuration file syntax, types, tables, and common patterns.
💎
Prisma
Complete Prisma ORM cheat sheet — schema, queries, migrations, and CLI.
🤖
GitHub Actions
Complete GitHub Actions cheat sheet — workflows, triggers, jobs, and CI/CD patterns.
📦
npm
Complete npm cheat sheet — package management, scripts, publishing, and configuration.
Supabase
Complete Supabase cheat sheet — auth, database, realtime, storage, and edge functions.
🪶
Apache
Complete Apache HTTP Server cheat sheet — virtual hosts, modules, rewrite rules, and SSL.
📡
HTTP Status Codes
Complete reference of all standard HTTP response status codes with descriptions and use cases.
🔤
ASCII Table
Complete ASCII character reference with decimal, hexadecimal, and character values.
🔧
Chrome DevTools
Essential Chrome DevTools shortcuts, commands, and workflows for web developers.
💧
Drizzle ORM
Complete Drizzle ORM reference for schema definition, queries, relations, migrations, and common patterns.
Vercel CLI
Complete Vercel CLI reference for deployment, project management, domains, environment variables, and configuration.
🔄
PM2
Production process manager for Node.js applications with built-in load balancer, monitoring, and zero-downtime reloads.
📺
Screen
GNU Screen terminal multiplexer for persistent sessions, window management, and remote work.
📦
Webpack
Module bundler for JavaScript applications — loaders, plugins, code splitting, optimization, and dev server.
Vite
Next-generation frontend build tool with instant HMR, native ES modules, and optimized production builds via Rollup.

📖 Free, searchable command reference. Bookmark this page for quick access.