PHP Cheat Sheet
Quick reference from FreeCodingCourses.com
Variables and types
$name = "Ada";- variables always start with $.
$count = 5;- int, no type keyword needed.
$price = 9.99;- float.
$ok = true;- bool, lowercase true or false.
$nada = null;- the null value.
gettype($x)- check a value's type at runtime.
(int) $s- cast a string to an integer.
Strings
"Hi $name"- double quotes interpolate variables.
'Hi $name'- single quotes print the literal text.
$a . $b- concatenate with a dot.
strlen($s)- length of the string.
strtoupper($s)- uppercase (strtolower for lower).
str_replace("a", "b", $s)- swap every occurrence.
explode(",", $s)- split a string into an array.
implode(", ", $arr)- join an array into a string.
Arrays
$a = [1, 2, 3];- an indexed array.
$a[] = 4;- push onto the end.
$user = ["name" => "Ada"];- an associative array.
$user["name"]- read a value by key.
count($a)- number of items.
in_array(2, $a)- true if the value is present.
array_keys($user)- all of the keys.
isset($user["email"])- true if the key exists and is not null.
Array functions
array_map(fn($n) => $n * 2, $a)- transform each item.
array_filter($a, fn($n) => $n > 0)- keep items that pass.
array_reduce($a, fn($c, $n) => $c + $n, 0)- fold to one value.
sort($a)- sort in place (rsort for descending).
array_merge($a, $b)- join two arrays.
array_column($rows, "name")- pluck one field from each row.
array_slice($a, 0, 3)- the first three items.
Control flow
if ($x > 0) { } elseif { } else { }- braces define the blocks.
foreach ($a as $item) { }- loop over the values.
foreach ($user as $k => $v)- loop keys and values.
for ($i = 0; $i < 5; $i++)- C-style counting loop.
while ($cond) { }- loop until the condition is false.
match ($code) { 200 => "ok", default => "?" }- PHP 8 match expression.
$x ?? "fallback"- null coalescing default.
Functions
function add($a, $b) { return $a + $b; }- define and return.
function add(int $a, int $b): int- typed params and return.
function greet($name = "friend")- default argument value.
$sq = fn($n) => $n * $n;- arrow function (PHP 7.4+).
function total(...$nums)- variadic: any number of args.
function () use ($outer) { }- pull an outer variable into a closure.
Superglobals and web
$_GET["q"]- a query string value from the URL.
$_POST["email"]- a submitted form field.
$_SERVER["REQUEST_METHOD"]- GET, POST, and so on.
$_SESSION["user_id"]- per-user session data.
json_encode($data)- array to a JSON string.
json_decode($s, true)- JSON string to an associative array.
htmlspecialchars($s)- escape output to block XSS.
Unlock the full PHP cheat sheet
You're seeing 2 of 7 sections. Drop your email to open the rest plus the gotchas, and save the whole thing as a printable PDF.
No spam, unsubscribe anytime. See our privacy policy.