Menu

PHP Cheat Sheet

Last updated

Hello World & tags

PHP code lives inside <?php ... ?> tags; everything outside is sent as plain output.

OperationSyntax
Open / close PHP<?php ... ?>
Print textecho "Hello, World!";
Print formattedprintf("%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.

OperationSyntax
Declare a variable$name = "Ada";
Constantconst PI = 3.14; or define("PI", 3.14);
Scalar typesint, float, string, bool
Null$x = null;
Check the typegettype($x), is_int($x), is_array($x)
Cast a type(int) $str, (string) $num
Variable exists / setisset($x), empty($x)
String interpolationecho "Hi $name";

Strings

Double quotes interpolate variables; single quotes are literal.

OperationSyntax
Concatenate$a . $b
Lengthstrlen($s)
Upper / lower casestrtoupper($s), strtolower($s)
Substringsubstr($s, 0, 5)
Find positionstrpos($s, "x")
Replacestr_replace("a", "b", $s)
Split into arrayexplode(",", $csv)
Join an arrayimplode(",", $arr)
Trim whitespacetrim($s)
Format a stringsprintf("%05.2f", $n)

Arrays (incl. associative)

One array type covers both indexed lists and key-value maps.

OperationSyntax
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";
Lengthcount($nums)
Check a keyisset($user["name"]), array_key_exists("name", $user)
Remove an elementunset($nums[1]);
Merge arraysarray_merge($a, $b)
Iterate key => valueforeach ($user as $k => $v) { ... }

Control flow

Conditionals and loops follow C-style syntax.

OperationSyntax
If / elseif / elseif ($x > 0) { ... } elseif (...) { ... } else { ... }
Ternary$y = $x > 0 ? "pos" : "neg";
Null coalescing$name = $_GET["name"] ?? "guest";
Switchswitch ($day) { case 1: ...; break; default: ... }
For loopfor ($i = 0; $i < 10; $i++) { ... }
While loopwhile ($x < 100) { ... }
Foreachforeach ($items as $item) { ... }
Match expression$r = match($x) { 1 => "one", default => "?" };
Break / continuebreak;, continue;

Functions

Functions can declare types, default values, and variadic parameters.

OperationSyntax
Basic functionfunction add($a, $b) { return $a + $b; }
Typed parameters & returnfunction add(int $a, int $b): int { ... }
Default valuefunction greet($name = "guest") { ... }
Variadic parametersfunction sum(...$nums) { ... }
Pass by referencefunction inc(&$x) { $x++; }
Anonymous function$f = function($x) { return $x * 2; };
Arrow function$f = fn($x) => $x * 2;
Use outer variablefunction() use ($n) { ... }

Superglobals

Built-in arrays available in every scope, mostly for request data.

SuperglobalWhat it holds
$_GETQuery-string parameters from the URL
$_POSTForm data sent via POST
$_REQUESTCombined $_GET, $_POST, and $_COOKIE
$_SESSIONPer-user session data (after session_start())
$_COOKIECookies sent by the browser
$_SERVERServer and request info (REQUEST_METHOD, etc.)
$_FILESUploaded file metadata
$_ENVEnvironment variables

Common array functions

PHP ships hundreds of array helpers; these are the workhorses.

FunctionWhat 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.

OperationSyntax
Define a classclass User { ... }
Property with visibilitypublic string $name;
Constructorfunction __construct($name) { $this->name = $name; }
Constructor promotionfunction __construct(public string $name) {}
Create an instance$u = new User("Ada");
Access a member$u->name, $u->save()
Static memberUser::$count, User::create()
Inheritanceclass Admin extends User { ... }
Interfaceinterface Saveable { public function save(); }
Implement an interfaceclass 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?
Yes. This PHP cheat sheet is completely free, with no sign-up required. Bookmark it and come back whenever you need to look up a string function, array helper, or superglobal.
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?
An associative array is a PHP array that uses named string keys instead of (or alongside) numeric indexes, like ["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).
Can I practice PHP online?
Yes. Open the PHP playground to run any snippet from this cheat sheet in your browser - no server or local PHP install needed. When you want structure, Coddy's free interactive PHP course takes you from variables and arrays to functions and OOP step by step.
Is this cheat sheet good for beginners?
Yes. It is organized from the most common topics (variables, strings, arrays, control flow) down to advanced ones (superglobals and OOP), so you can use the top sections on day one and grow into the rest.
Coddy programming languages illustration

Learn PHP with Coddy

GET STARTED