📖 Guide
PHP — Complete Reference
Comprehensive PHP cheat sheet covering syntax, OOP, arrays, PDO, and modern PHP 8.x features.
121 commands across 11 categories
BasicsStringsArraysFunctionsClasses & OOPError HandlingFile I/ODatabase (PDO)SuperglobalsCommon FunctionsModern PHP (8.x)
Basics
| Command | Description |
|---|---|
<?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) $vare.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
| Command | Description |
|---|---|
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
| Command | Description |
|---|---|
$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
| Command | Description |
|---|---|
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
| Command | Description |
|---|---|
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
| Command | Description |
|---|---|
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
| Command | Description |
|---|---|
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)
| Command | Description |
|---|---|
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
| Command | Description |
|---|---|
$_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
| Command | Description |
|---|---|
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)
| Command | Description |
|---|---|
$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+) |
📖 Free, searchable command reference. Bookmark this page for quick access.