PHP Cheat Sheet
Last updated
Hello World & tags
PHP code lives inside <?php ... ?> tags; everything outside is sent as plain output.
| Operation | Syntax |
|---|---|
| Open / close PHP | <?php ... ?> |
| Print text | echo "Hello, World!"; |
| Print formatted | printf("%d items", $n); |
| Short echo (in HTML) | <?= $name ?> |
| Single-line comment | // comment or # comment |
| Block comment | /* comment */ |
| Statement terminator | ; |
| Run a file (CLI) | php index.php |
Variables & types
Variables start with $ and are dynamically typed.
| Operation | Syntax |
|---|---|
| Declare a variable | $name = "Ada"; |
| Constant | const PI = 3.14; or define("PI", 3.14); |
| Scalar types | int, float, string, bool |
| Null | $x = null; |
| Check the type | gettype($x), is_int($x), is_array($x) |
| Cast a type | (int) $str, (string) $num |
| Variable exists / set | isset($x), empty($x) |
| String interpolation | echo "Hi $name"; |
Strings
Double quotes interpolate variables; single quotes are literal.
| Operation | Syntax |
|---|---|
| Concatenate | $a . $b |
| Length | strlen($s) |
| Upper / lower case | strtoupper($s), strtolower($s) |
| Substring | substr($s, 0, 5) |
| Find position | strpos($s, "x") |
| Replace | str_replace("a", "b", $s) |
| Split into array | explode(",", $csv) |
| Join an array | implode(",", $arr) |
| Trim whitespace | trim($s) |
| Format a string | sprintf("%05.2f", $n) |
Arrays (incl. associative)
One array type covers both indexed lists and key-value maps.
| Operation | Syntax |
|---|---|
| Indexed array | $nums = [1, 2, 3]; |
| Associative array | $user = ["name" => "Ada", "age" => 30]; |
| Access an element | $nums[0], $user["name"] |
| Append | $nums[] = 4; |
| Set a key | $user["role"] = "admin"; |
| Length | count($nums) |
| Check a key | isset($user["name"]), array_key_exists("name", $user) |
| Remove an element | unset($nums[1]); |
| Merge arrays | array_merge($a, $b) |
| Iterate key => value | foreach ($user as $k => $v) { ... } |
Control flow
Conditionals and loops follow C-style syntax.
| Operation | Syntax |
|---|---|
| If / elseif / else | if ($x > 0) { ... } elseif (...) { ... } else { ... } |
| Ternary | $y = $x > 0 ? "pos" : "neg"; |
| Null coalescing | $name = $_GET["name"] ?? "guest"; |
| Switch | switch ($day) { case 1: ...; break; default: ... } |
| For loop | for ($i = 0; $i < 10; $i++) { ... } |
| While loop | while ($x < 100) { ... } |
| Foreach | foreach ($items as $item) { ... } |
| Match expression | $r = match($x) { 1 => "one", default => "?" }; |
| Break / continue | break;, continue; |
Functions
Functions can declare types, default values, and variadic parameters.
| Operation | Syntax |
|---|---|
| Basic function | function add($a, $b) { return $a + $b; } |
| Typed parameters & return | function add(int $a, int $b): int { ... } |
| Default value | function greet($name = "guest") { ... } |
| Variadic parameters | function sum(...$nums) { ... } |
| Pass by reference | function inc(&$x) { $x++; } |
| Anonymous function | $f = function($x) { return $x * 2; }; |
| Arrow function | $f = fn($x) => $x * 2; |
| Use outer variable | function() use ($n) { ... } |
Superglobals
Built-in arrays available in every scope, mostly for request data.
| Superglobal | What it holds |
|---|---|
$_GET | Query-string parameters from the URL |
$_POST | Form data sent via POST |
$_REQUEST | Combined $_GET, $_POST, and $_COOKIE |
$_SESSION | Per-user session data (after session_start()) |
$_COOKIE | Cookies sent by the browser |
$_SERVER | Server and request info (REQUEST_METHOD, etc.) |
$_FILES | Uploaded file metadata |
$_ENV | Environment variables |
Common array functions
PHP ships hundreds of array helpers; these are the workhorses.
| Function | What it does |
|---|---|
array_map($fn, $arr) | Transform every element |
array_filter($arr, $fn) | Keep elements where the callback is true |
array_reduce($arr, $fn, $init) | Fold to a single value |
in_array($v, $arr) | Check if a value is present |
array_keys($arr) / array_values($arr) | Get keys or values |
sort($arr) / rsort($arr) | Sort in place (asc / desc) |
usort($arr, $cmp) | Sort with a custom comparator |
array_slice($arr, 1, 3) | Extract a portion |
array_push($arr, $v) / array_pop($arr) | Add / remove from the end |
Classes & OOP
PHP supports classes, inheritance, interfaces, and visibility modifiers.
| Operation | Syntax |
|---|---|
| Define a class | class User { ... } |
| Property with visibility | public string $name; |
| Constructor | function __construct($name) { $this->name = $name; } |
| Constructor promotion | function __construct(public string $name) {} |
| Create an instance | $u = new User("Ada"); |
| Access a member | $u->name, $u->save() |
| Static member | User::$count, User::create() |
| Inheritance | class Admin extends User { ... } |
| Interface | interface Saveable { public function save(); } |
| Implement an interface | class User implements Saveable { ... } |
The PHP syntax you reach for most, on one page. This PHP cheat sheet is a quick reference for the core language - variables and types, strings, arrays (including associative arrays), control flow, functions, the superglobals like $_GET and $_POST, and classes.
Everything here is standard PHP that runs on modern versions. Copy what you need, or try every snippet live in the PHP playground - no server to set up.
PHP cheat sheet FAQ
Is this PHP cheat sheet free?
What is the difference between == and === in PHP?
== is loose comparison: it converts the operands to a common type before comparing, so 0 == "0" and even 0 == "" can behave surprisingly across versions. === is strict comparison: it returns true only when the values are equal and of the same type, so 0 === "0" is false. Prefer === to avoid type-juggling bugs.What are associative arrays in PHP?
["name" => "Ada", "age" => 30]. PHP has a single array type that doubles as both an ordered list and a key-value map, so you access values by key with $user["name"] and iterate with foreach ($user as $key => $value).