PHP Cheat Sheet

Free PHP cheat sheet: syntax, arrays, OOP, database functions, and web essentials in one quick reference.

Basics

ConceptSyntaxExample
Variable$name = value;$count = 0;
Constantdefine('NAME', value)define('PI', 3.14);
Printecho / printecho "Hello $name";
Array$arr = [1, 2, 3]$fruits = ['apple', 'banana'];
Type casting(int), (string), (array)$num = (int) "42"; // 42

Learn it in a lesson: Variables & Data Types · Introduction to PHP · Arrays & Collections · Type Juggling & Casting

Strings

ConceptSyntaxExample
Concatenate$a . $b$full = $first . ' ' . $last;
Interpolate
Double quotes interpolate, single quotes do not. Braces are needed for array access.
"Hello $name"echo "Total: {$order['total']}";
Length
strlen counts BYTES. Use mb_strlen for anything that might not be ASCII.
strlen($s) | mb_strlen($s)mb_strlen('Creme') // 5
Casestrtolower | strtoupper | ucfirstucfirst('ada') // 'Ada'
Split and joinexplode($sep, $s) | implode($sep, $a)explode(',', 'a,b') // ['a','b']
Replacestr_replace($find, $with, $s)str_replace(' ', '-', $title);
Contains
PHP 8.0+. Before that it was strpos() !== false.
str_contains($h, $n)str_contains($email, '@')
Functionsstrlen, strtoupper, substrecho strlen('hello'); // 5
Regexpreg_match, preg_replacepreg_match('/\d+/', $str, $m);

Learn it in a lesson: Strings & String Functions · Regular Expressions (preg)

OOP

ConceptSyntaxExample
Classclass Name { }class Dog { public $name; }
Constructor__construct(params)function __construct(public string $name) {}
Inheritanceclass B extends A { }class Puppy extends Dog {}
Interfaceinterface Name { }interface Drawable { public function draw(); }

Learn it in a lesson: Object-Oriented PHP · Advanced OOP Patterns: Factory, Singleton, Strategy & Repository

Arrays

ConceptSyntaxExample
Associative['key' => 'val']$user = ['name' => 'Alice'];
Maparray_map($fn, $a)array_map(fn($n) => $n * 2, [1,2]) // [2,4]
Filter
With no callback it drops every falsy value — and it PRESERVES the keys.
array_filter($a, $fn)array_filter([1,0,2]) // keeps 1 and 2
Reducearray_reduce($a, $fn, $init)array_reduce([1,2,3], fn($c, $n) => $c + $n, 0) // 6
Keys and values
array_values re-indexes, which is how you undo array_filter's gaps.
array_keys | array_valuesarray_values(['a'=>1]) // [1]
Does key exist
isset is false when the value is null; array_key_exists is not.
isset($a[$k]) | array_key_exists($k, $a)isset($row['id'])
Sort
These sort IN PLACE and return a bool, not the array.
sort | usort | ksortusort($users, fn($a, $b) => $a['age'] <=> $b['age']);
Functionsarray_map, array_filter, array_mergearray_map(fn($x) => $x*2, $arr);

Learn it in a lesson: Arrays & Collections

Database (PDO)

ConceptSyntaxExample
Connectnew PDO(dsn, user, pass)$pdo = new PDO('mysql:host=localhost;dbname=app', 'root', '');
Prepared stmt$pdo->prepare(sql)$stmt = $pdo->prepare('SELECT * FROM users WHERE id = ?');
Execute$stmt->execute([vals])$stmt->execute([1]); $row = $stmt->fetch();

Learn it in a lesson: Database Integration (MySQL)

Requests & Safety

ConceptSyntaxExample
Query string
Never trust it. Cast or validate before use.
$_GET['key']$page = (int)($_GET['page'] ?? 1);
Form body$_POST['key']$email = trim($_POST['email'] ?? '');
Session
session_start() must run before any output is sent.
session_start(); $_SESSION[]session_start(); $_SESSION['uid'] = 7;
Uploaded file
Check ['error'] === UPLOAD_ERR_OK first, and never trust ['name'].
$_FILES['field']move_uploaded_file($_FILES['cv']['tmp_name'], $dest);
Escape for HTML
This is what stops XSS. Escape on output, every time.
htmlspecialchars($s, ENT_QUOTES)echo htmlspecialchars($comment, ENT_QUOTES);
Hash a password
Never md5 or sha1 a password, and never write your own.
password_hash / password_verifypassword_verify($input, $row['hash'])

Learn it in a lesson: Forms & User Input · Sessions & Cookies · Password Hashing, Argon2 & Secure Credential Storage