PHP Language Cheat Sheet
A searchable reference of modern PHP syntax and what each snippet does.
| Snippet | What it does |
|---|---|
<?php ... ?> | Open and close a block of PHP code; the closing tag is optional in a pure-PHP file. |
echo "Hello"; | Output one or more strings; echo is a language construct, not a function. |
$name = "Ada"; | Declare a variable; names start with a dollar sign and are case-sensitive. |
$i = 42; $f = 1.5; $s = "hi"; $b = true; | Scalar types are int, float, string, and bool, alongside array, object, and null. |
$full = $a . " " . $b; | Join strings with the dot operator; PHP concatenates with . and not with +. |
$msg = <<<EOT Hello $name EOT; | Heredoc: a multi-line string that interpolates variables just like double quotes. |
define("MAX", 100); | Define a global constant at runtime with the define() function. |
const VERSION = "1.0"; | Declare a compile-time constant with const; also used for class constants. |
$x = $a ?? "default"; | Null coalescing: return the left side if it is set and not null, otherwise the right side. |
$a = [1, 2, 3]; | Create a zero-indexed array with the short bracket syntax. |
$m = ["id" => 7, "name" => "Ada"]; | Create an associative array mapping keys to values with the => arrow. |
$a[] = 4; | Append a value to the end of an array, the same as array_push for a single value. |
count($a) | Return the number of elements in an array. |
foreach ($a as $v) { echo $v; } | Loop over each value of an array. |
array_map("strtoupper", $a) | Return a new array with the callback applied to every element. |
array_filter($a, fn($x) => $x > 0) | Keep only the elements for which the callback returns true. |
array_merge($a, $b) | Combine two or more arrays; later string keys overwrite earlier ones. |
in_array(2, $a, true) | Return true if a value exists in the array; the third argument enables strict type checking. |
array_keys($m) | Return all the keys of an array as a new array. |
implode(", ", $a) | Join array elements into a single string with a separator. |
explode(",", "a,b,c") | Split a string into an array on a delimiter. |
strlen($s) | Return the number of bytes in a string, which is not always the character count. |
str_replace("a", "b", $s) | Replace every occurrence of a substring with another. |
substr($s, 0, 5) | Return part of a string given a start offset and an optional length. |
strpos($s, "x") | Return the index of the first match or false if none; compare with === to test. |
trim($s) | Remove whitespace, or given characters, from both ends of a string. |
strtolower($s) | Return the string with all ASCII letters lowercased. |
sprintf("%0.2f", $n) | Return a string built from a format template; printf outputs it directly. |
str_contains($s, "ip") | Return true if the string contains the substring; added in PHP 8.0. |
explode(" ", $sentence) | Split a string into pieces on a separator, returning an array. |
if ($a) { ... } elseif ($b) { ... } else { ... } | Run the first branch whose condition is true. |
for ($i = 0; $i < 10; $i++) { ... } | Loop with an initializer, a condition, and a step. |
foreach ($m as $k => $v) { ... } | Loop over an array reading both the key and the value. |
while ($cond) { ... } | Repeat the block while the condition stays true. |
switch ($x) { case 1: ...; break; default: ...; } | Branch on a value with loose comparison; add break to stop fall-through. |
$r = match($x) { 1 => "one", default => "?" }; | Return a value by strict comparison with no fall-through; added in PHP 8.0. |
$r = $ok ? "yes" : "no"; | Ternary: a compact if and else that returns one of two values. |
$config["x"] ??= "default"; | Assign the right side only if the left side is null or unset; added in PHP 7.4. |
function add($a, $b) { return $a + $b; } | Declare a named function. |
return $value; | Send a value back to the caller and stop the function. |
function greet($name = "world") { ... } | Give a parameter a default value so callers can omit it. |
function sum(int $a, int $b): int { ... } | Declare parameter and return types; PHP enforces them at call time. |
$f = fn($x) => $x * 2; | Arrow function: a one-expression closure that captures outer variables; added in PHP 7.4. |
function sum(...$nums) { ... } | Variadic: collect any number of arguments into an array with the spread token. |
greet(name: "Ada"); | Named arguments: pass values by parameter name in any order; added in PHP 8.0. |
class User { ... } | Define a class, the blueprint from which objects are created. |
public function __construct($name) { ... } | Constructor method that runs automatically when an object is created with new. |
private string $name; | Visibility: public is reachable anywhere, protected within subclasses, private only inside the class. |
class Admin extends User { ... } | Create a subclass that inherits properties and methods from a parent class. |
class Circle implements Shape { ... } | Implement an interface, a contract of methods that the class must define. |
public static function make(): self { ... } | A static member belongs to the class itself; call it with ClassName::method(). |
$this->name = $name; | Inside a method, $this refers to the current object instance. |
namespace App\Models; | Group classes under a namespace to avoid name clashes between libraries. |
use App\Models\User; | Import a class from a namespace so you can refer to it by its short name. |
trait Loggable { ... } | Define a reusable bundle of methods that classes pull in with the use keyword. |
No snippets match your search.
Runs entirely in your browser. Nothing you type is sent anywhere; open DevTools and watch the Network tab to verify zero requests.
What this tool does
This is a searchable quick reference for the PHP language, from basic syntax and variables through arrays, strings, control flow, functions, and object-oriented classes. Each row pairs an exact snippet with a plain-English note on what it does, and everything targets modern PHP 8.x. Type in the filter box to search across both columns, or tap a category button to focus on one topic. The whole list is built into the page, so it works offline and sends nothing anywhere.
How to use it
Start typing in the Filter box. Entering match jumps
to the match expression; entering array surfaces the array helpers like
array_map and array_filter; entering trait
shows the object-oriented reuse tools. The category buttons (Basics,
Arrays, Strings, Control flow, Functions, OOP) narrow the table to one family and
combine with the text filter, so you can pick OOP and type static to zero
in on class members. Clear the box to see the full sheet again.
Common use cases
- Recalling the exact form of a snippet you use rarely, like
sprintfor thematchexpression. - Copying a correct snippet into your editor instead of guessing the syntax.
- Checking modern PHP 8 features such as named arguments, arrow functions, and
str_contains. - Teaching a teammate the difference between an indexed array and an associative array.
- Reviewing the core language before an interview or a new job.
Common pitfalls
- Loose comparison with ==. The
==operator juggles types, so surprising values can compare equal. Prefer===for a strict comparison that also checks the type. - Concatenating with plus. PHP joins strings with the dot operator,
., while+is numeric addition. Using+on two strings tries to add them as numbers. - strpos returning zero. When a match is at the start,
strposreturns0, which is falsy. Always test the result with=== falserather than a plain truthiness check. - Mixing up array keys. An indexed and an associative array are the
same type, so an accidental string key or a gap in the numbers can change how
foreachand functions likearray_mergebehave.
Frequently asked questions
- What is the null coalescing operator in PHP?
- The null coalescing operator ?? returns its left operand when that value exists and is not null, and otherwise returns the right operand. It is a safe way to read a value that might be missing, such as $name = $data["name"] ?? "guest", because it does not raise a warning when the key is absent. The related ??= operator assigns the right side only when the left side is currently null or unset.
- What is the difference between an indexed and an associative array?
- An indexed array uses automatic integer keys starting at zero, like [10, 20, 30], and is the natural fit for an ordered list. An associative array uses keys you choose, usually strings, like ["id" => 7, "name" => "Ada"], and works like a dictionary or map. In PHP both are the same underlying ordered-map type, so a single array can even mix integer and string keys.
- What is the match expression and how does it differ from switch?
- The match expression, added in PHP 8.0, compares a subject against arms using strict === comparison and returns a value, so you can write $label = match($code) { 200 => "OK", default => "?" }. Unlike switch it has no fall-through, needs no break, and throws an UnhandledMatchError when nothing matches and there is no default. switch by contrast uses loose comparison, runs statements rather than returning a value, and falls through until a break.
- What is the difference between single and double quotes in PHP strings?
- Single-quoted strings are nearly literal: PHP does not expand variables inside them and only interprets the escapes for a backslash and a single quote. Double-quoted strings interpolate variables, so "Hi $name" inserts the value of $name, and they support escapes such as newline and tab. Single quotes are marginally faster and are the right choice when you want the text exactly as typed.
- What are traits in PHP?
- A trait is a reusable bundle of methods (and properties) that a class pulls in with the use keyword, giving horizontal code reuse without inheritance. Because a class can extend only one parent but use many traits, traits let you share behavior such as logging or timestamps across unrelated classes. When two traits define the method name, you resolve the conflict explicitly with insteadof and as.
- Does this cheat sheet send my searches anywhere?
- No. The entire snippet list is baked into the page and every filter runs in your browser with JavaScript, so nothing you type is transmitted to any server. Open your browser DevTools and watch the Network tab while you search to confirm there are zero requests.
Cite this tool
For academic, journalistic, or technical references. Pick a format:
Citations use 2026 as the publication year. Access date is left as a fillable placeholder where the citation style expects one.