PHP Cheatsheet
A dense, organized reference for everyday PHP syntax and built-in functions, meant as a fast lookup once you've already read through the rest of this section. Each table covers one category with the syntax or function signature and a short description of what it does.
Syntax Basics
Syntax | What it does |
|---|---|
<?php ... ?> | Opening and closing PHP tags |
$name = value; | Variable assignment (variables always start with $) |
// or # | Single-line comment |
/* ... */ | Multi-line comment |
. or .= | String concatenation / concatenate-and-assign |
echo, print | Output a value (echo takes multiple args, print returns 1) |
if / elseif / else | Conditional branching |
switch / match | Multi-branch comparison (match is strict and returns a value) |
for ($i = 0; $i < N; $i++) | Counter-based loop |
foreach ($arr as $k => $v) | Iterate an array by key and value |
while / do-while | Condition-based loop, checked before/after the body |
function name(type $arg): returnType {} | Function declaration with types |
fn ($x) => $x * 2 | Arrow function (short closure, auto-captures outer scope) |
declare(strict_types=1); | Disable automatic type coercion for this file |
namespace App\Billing; | Declare the namespace for this file |
use App\Billing\Invoice; | Import a class from another namespace |
Types and Type Checking
Function / operator | What it does |
|---|---|
gettype($var) | Returns the type as a string ("integer", "string", ...) |
is_int(), is_float(), is_string() | Type-check a scalar value |
is_array(), is_object(), is_bool() | Type-check a compound value |
is_null(), is_numeric(), is_callable() | Additional common type checks |
(int), (float), (string), (bool), (array) | Explicit cast to another type |
settype($var, "integer") | Cast a variable in place |
intval(), floatval(), strval(), boolval() | Cast and return a new value of that type |
?type | Nullable type declaration, e.g. ?int allows int or null |
int|string | Union type declaration (PHP 8+) |
String Functions
Function | What it does |
|---|---|
strlen($s) | Length of a string in bytes |
strtolower($s), strtoupper($s) | Change case |
ucfirst($s), ucwords($s) | Capitalize first letter / first letter of each word |
trim($s), ltrim($s), rtrim($s) | Remove whitespace (or given characters) from ends |
substr($s, $start, $length) | Extract a portion of a string |
str_replace($search, $replace, $s) | Replace all occurrences of a substring |
str_contains($s, $needle) | Check whether a string contains a substring (PHP 8+) |
str_starts_with($s, $needle) | Check whether a string starts with a substring (PHP 8+) |
str_ends_with($s, $needle) | Check whether a string ends with a substring (PHP 8+) |
explode($delimiter, $s) | Split a string into an array by a delimiter |
implode($glue, $array) | Join an array of strings into one string |
sprintf($format, ...$args) | Build a formatted string without printing it |
str_pad($s, $length, $pad) | Pad a string to a target length |
str_repeat($s, $times) | Repeat a string a number of times |
strpos($haystack, $needle) | Position of the first occurrence, or false if not found |
htmlspecialchars($s) | Escape HTML special characters for safe output |
trim(preg_replace("/\s+/", " ", $s)) | Collapse repeated whitespace to single spaces |
Array Functions
Function | What it does |
|---|---|
count($array) | Number of elements in an array |
array_push($array, $value) | Append a value to the end (or use $array[] = $value) |
array_pop($array) | Remove and return the last element |
array_shift($array) | Remove and return the first element (re-indexes keys) |
array_unshift($array, $value) | Prepend a value to the start |
array_map($callback, $array) | Apply a callback to every element, returning a new array |
array_filter($array, $callback) | Keep only elements the callback returns true for |
array_reduce($array, $callback, $initial) | Fold an array down to a single accumulated value |
array_merge($a, $b) | Combine two arrays into one |
array_keys($array), array_values($array) | Get just the keys, or just the values |
in_array($needle, $array) | Check whether a value exists in an array |
array_key_exists($key, $array) | Check whether a key exists (works with null values too) |
sort($array), rsort($array) | Sort by value, ascending / descending, re-indexing keys |
asort($array), ksort($array) | Sort preserving keys, by value / by key |
usort($array, $callback) | Sort using a custom comparison callback |
array_slice($array, $offset, $length) | Extract a portion of an array |
array_unique($array) | Remove duplicate values |
array_reverse($array) | Reverse the order of elements |
array_column($array, $column) | Pull a single column of values out of an array of arrays |
array_combine($keys, $values) | Build an array pairing one array as keys, another as values |
Math Functions
Function | What it does |
|---|---|
abs($n) | Absolute value |
round($n, $precision) | Round to the given number of decimal places |
floor($n), ceil($n) | Round down / round up to the nearest integer |
min(...$values), max(...$values) | Smallest / largest of the given values |
pow($base, $exp), $base ** $exp | Exponentiation |
sqrt($n) | Square root |
intdiv($a, $b) | Integer division, discarding the remainder |
$a % $b | Modulo (remainder of division) |
rand($min, $max) | Random integer in a range (use random_int for security-sensitive code) |
array_sum($array), array_product($array) | Sum / product of all values in an array |
Common Superglobals
Superglobal | What it holds |
|---|---|
$_GET | Query string parameters from the URL |
$_POST | Form data submitted with a POST request |
$_REQUEST | Merged $_GET, $_POST, and $_COOKIE (avoid — ambiguous source) |
$_SESSION | Data persisted for the current user across requests |
$_COOKIE | Cookies sent by the browser with the request |
$_SERVER | Server and request environment info (headers, method, URI, etc.) |
$_FILES | Metadata and temp paths for uploaded files |
$_ENV | Environment variables available to the PHP process |
$GLOBALS | Access to all variables in the global scope from any scope |
OOP Syntax
Class, interface, and trait syntax at a glance
<?php
declare(strict_types=1);
interface Payable
{
public function amount(): float;
}
trait Timestamped
{
private ?DateTimeImmutable $createdAt = null;
public function markCreated(): void
{
$this->createdAt = new DateTimeImmutable();
}
}
abstract class Document
{
abstract public function render(): string;
}
final class Invoice extends Document implements Payable
{
use Timestamped;
public function __construct(
private readonly float $total,
private array $lines = [],
) {
}
public function amount(): float
{
return $this->total;
}
public function render(): string
{
return sprintf('Invoice for %.2f', $this->total);
}
public static function empty(): static
{
return new static(0.0);
}
}
$invoice = new Invoice(199.99);
echo $invoice->render();Visibility and Modifiers
Keyword | What it does |
|---|---|
public | Accessible from anywhere |
protected | Accessible from within the class and its subclasses |
private | Accessible only within the declaring class |
static | Belongs to the class itself, not to any instance |
readonly | Property can be set once (in the constructor) and never modified after (PHP 8.1+) |
final | Prevents a class from being extended, or a method from being overridden |
abstract | Declares a method with no body that subclasses must implement |
Error Handling
try / catch / finally and throwing exceptions
<?php
try {
$result = riskyOperation();
} catch (InvalidArgumentException $e) {
// handle a specific, expected failure
error_log($e->getMessage());
} catch (Throwable $e) {
// catch-all for anything else, including Errors
error_log('Unexpected: ' . $e->getMessage());
} finally {
// always runs, whether an exception was thrown or not
cleanup();
}
function withdraw(float $amount, float $balance): float
{
if ($amount > $balance) {
throw new RuntimeException('Insufficient funds');
}
return $balance - $amount;
}Concept | Notes |
|---|---|
Exception | Base class for expected, recoverable error conditions |
Error | Base class for internal engine errors (TypeError, DivisionByZeroError, ...) |
Throwable | Common interface implemented by both Exception and Error — catch this to catch anything |
set_error_handler() | Register a custom handler for traditional PHP warnings/notices |
set_exception_handler() | Register a fallback handler for uncaught exceptions |
Useful One-Liners
Small, frequently reached-for snippets
<?php
// Null coalescing: use a default when a value is null/unset
$name = $_GET['name'] ?? 'Guest';
// Null coalescing assignment: set only if not already set
$config['timeout'] ??= 30;
// Null-safe method chaining: skip the call if the object is null
$city = $user?->address?->city;
// Spread operator: unpack an array into function arguments
function sum3($a, $b, $c) { return $a + $b + $c; }
echo sum3(...[1, 2, 3]);
// Destructuring: pull array values into named variables
['name' => $name, 'age' => $age] = ['name' => 'Ada', 'age' => 30];
// Ternary shorthand: fall back to $b if $a is falsy
$value = $a ?: $b;
// One-line JSON encode/decode
$json = json_encode(['status' => 'ok']);
$data = json_decode($json, true);
// Match expression: strict comparison, returns a value
$label = match (true) {
$score >= 90 => 'A',
$score >= 80 => 'B',
default => 'C',
};