PHP Cheat Sheet
Output, strings, arrays, functions, forms, sessions, dates, regex, files, JSON, PDO, OOP, Composer, passwords, security and APIs on one printable page.
Tags, variables & strings
| Syntax | What it does | Lesson |
|---|---|---|
<?php ... ?> <?= $x ?> | Code block / print a value | Introduction |
php -S localhost:8000 | Start a local server | Introduction |
$name = "Ana"; | Create a variable | Variables |
"Hi $name" 'Hi ' . $name | Interpolate / join | Variables |
strlen() strtoupper() trim() str_replace() | String helpers | Variables |
Conditions, loops & arrays
Functions & includes
Forms & validation
| Syntax | What it does | Lesson |
|---|---|---|
$_GET['q'] ?? '' $_POST['email'] ?? '' | Read form values | Forms |
$_SERVER['REQUEST_METHOD'] === 'POST' | Was the form submitted? | Forms |
htmlspecialchars($s) | Escape output (prevent XSS) | Forms |
header('Location: thanks.php'); exit; | Redirect after POST | Forms |
filter_var($e, FILTER_VALIDATE_EMAIL) | Validate an email | Validation |
hash_equals($_SESSION['token'], $t) | Check a CSRF token | Validation |
Sessions, cookies & files
| Syntax | What it does | Lesson |
|---|---|---|
session_start(); $_SESSION['id'] = 5; | Remember data on the server | Sessions |
session_destroy(); | Log out | Sessions |
setcookie('theme', 'dark', [...]); $_COOKIE['theme'] | Set / read a cookie | Sessions |
file_get_contents($p) file_put_contents($p, $s, FILE_APPEND) | Read / write files | Files |
fgetcsv($handle) | Read a CSV row | Files |
move_uploaded_file($tmp, $dest) | Save an upload | Files |
JSON & databases
| Syntax | What it does | Lesson |
|---|---|---|
json_encode($data, JSON_PRETTY_PRINT) | PHP to JSON | JSON |
json_decode($json, true) | JSON to array | JSON |
header('Content-Type: application/json'); | Return JSON | JSON |
new PDO($dsn, $user, $pass, [...]) | Connect to a database | PDO |
$s = $pdo->prepare('... WHERE id = ?'); $s->execute([$id]); | Prepared statement | PDO |
$s->fetchAll() $pdo->lastInsertId() | Read rows / new id | PDO |
Classes & exceptions
| Syntax | What it does | Lesson |
|---|---|---|
class P { public function __construct(private string $n) {} } | Class with promoted property | Classes |
$p = new P('x'); $p->method(); | Create and use an object | Classes |
class B extends A parent::method() | Inheritance | Classes |
interface I { } class C implements I | Contracts | Classes |
try { } catch (Exception $e) { } finally { } | Handle errors | Exceptions |
throw new InvalidArgumentException('msg'); | Report a problem | Exceptions |
Strings & array functions
| Syntax | What it does | Lesson |
|---|---|---|
trim($s) strtolower($s) ucwords($s) | Tidy text | String Functions |
str_contains($s, "x") strpos($s, "x") === false | Search text | String Functions |
substr($s, 0, 10) mb_strlen($s) | Part of a string, real length | String Functions |
sprintf("%s: £%.2f", $n, $p) number_format($n, 2) | Format values | String Functions |
array_map(fn($x) => $x * 2, $a) | Transform every item | Array Functions |
array_filter($a, fn($x) => $x > 0) | Keep matching items | Array Functions |
usort($a, fn($x, $y) => $x['p'] <=> $y['p']) | Sort records | Array Functions |
array_column($rows, 'name', 'id') | Pull out a field | Array Functions |
Dates & regex
| Syntax | What it does | Lesson |
|---|---|---|
date('Y-m-d H:i:s') | Current date and time | Dates & Times |
new DateTimeImmutable('2024-07-05') | Create a date | Dates & Times |
$d->modify('+3 days') $a->diff($b)->days | Move a date, days between | Dates & Times |
preg_match('/^[a-z]{3,15}$/i', $s) | Validate by pattern | Regular Expressions |
preg_match_all('/#(\w+)/', $s, $m) | Find every match | Regular Expressions |
preg_replace('/\s+/', ' ', $s) | Replace by pattern | Regular Expressions |
OOP & Composer
| Syntax | What it does | Lesson |
|---|---|---|
abstract class Shape { abstract public function area(): float; } | Abstract class | Interfaces, Traits & Enums |
class Card implements PaymentMethod | Implement an interface | Interfaces, Traits & Enums |
trait Loggable { } and use Loggable; | Share methods | Interfaces, Traits & Enums |
enum Status: string { case Paid = 'paid'; } | Fixed set of values | Interfaces, Traits & Enums |
namespace App\Models; use App\Models\User; | Namespaces | Namespaces & Composer |
composer require vendor/package | Install a package | Namespaces & Composer |
require __DIR__ . '/vendor/autoload.php'; | Autoload classes | Namespaces & Composer |
Apps, security & APIs
| Syntax | What it does | Lesson |
|---|---|---|
header('Location: index.php'); exit; | Redirect after POST | CRUD App |
password_hash($p, PASSWORD_DEFAULT) | Hash a password | Login & Passwords |
password_verify($typed, $hash) | Check a password | Login & Passwords |
session_regenerate_id(true) | New session id at login | Login & Passwords |
htmlspecialchars($s, ENT_QUOTES, 'UTF-8') | Escape output (XSS) | Web Security |
hash_equals($_SESSION['csrf'], $_POST['csrf']) | Check a CSRF token | Web Security |
json_decode(file_get_contents('php://input'), true) | Read a JSON request | REST API |
http_response_code(201) | Set the status code | REST API |
How to use this PHP cheat sheet
This PHP cheat sheet collects the syntax you'll reach for most often, in the same order as the course: tags and output, variables and strings, conditions, loops, arrays and array functions, functions, includes, forms and validation, sessions and cookies, dates, regular expressions, files, JSON, PDO, classes, interfaces and enums, exceptions, Composer, security and APIs. Each row links to the lesson that explains it with examples and common mistakes.
Keep it open while you build pages with PHP's built-in server or a package like XAMPP. When you can't remember which array function keeps keys while sorting, how to append to a file, or the shape of a prepared statement, a quick look answers it. Type a function name into the filter box to jump straight to it, or print the page as a one-sheet reference.
PHP gotchas worth remembering
- Use === rather than ==. Loose comparison converts types, so
"abc" == 0was true before PHP 8 and still trips people up with other values. Strict comparison checks the type too. - strpos can return 0. A match at the start of the string returns 0, which is falsy. Test with
!== false, or usestr_containsin PHP 8. - Single quotes don't interpolate.
'Hi $name'prints the dollar sign literally. Use double quotes or concatenation. - Escape on output. Wrap anything from users in
htmlspecialchars()before printing it, and use prepared statements with PDO for every query. - Sessions start before output.
session_start()andheader()must run before any HTML, even a blank line, is sent.
Revisit the linked lessons for anything that surprises you, then check yourself with the PHP quiz.
The PHP lessons behind this cheat sheet
Beginner
Intermediate
Advanced
Fundamentals reference
- 26PHP Constants and define()
- 27PHP Magic Constants
- 28PHP Numbers and Math Functions
- 29PHP Increment and Decrement Operators
- 30PHP Shorthand If and Ternary Operators
- 31PHP switch vs match
- 32PHP Variable Scope and $GLOBALS
- 33PHP Superglobals: $_SERVER, $_REQUEST and $_ENV
- 34PHP isset(), empty() and unset()
- 35PHP Built-in Functions Reference
Arrays and functions reference
- 36PHP Indexed vs Associative Arrays
- 37PHP Multidimensional Array Operations
- 38PHP Array Sorting Functions Reference
- 39PHP Callback Functions and Anonymous Functions
- 40PHP Arrow Functions
- 41PHP Variable-Length and Named Arguments
- 42PHP Iterables and Generators
- 43PHP Type Declarations and Return Types
- 44PHP Null Coalescing and Nullsafe Operators
- 45PHP Enums and Readonly Properties
OOP reference
- 46PHP Abstract Classes
- 47PHP Class Constants
- 48PHP Static Methods and Static Properties
- 49PHP Constructors and Destructors
- 50PHP Traits and Trait Conflict Resolution
- 51PHP Late Static Binding
- 52PHP Magic Methods
- 53PHP Object Iteration and Iterators
- 54PHP Namespaces and Aliases
- 55PHP Object Cloning and Comparison
Web requests and data reference
- 56PHP Filters and Validation Filters
- 57Advanced File Handling and File Permissions
- 58File Upload Security and MIME-Type Validation
- 59CSV Processing
- 60XML Processing with SimpleXML
- 61XML Processing with DOM
- 62XML Parsing with Expat
- 63AJAX with PHP
- 64PHP Live Search with AJAX
- 65HTTP Headers, Redirects and Response Codes
- 66Email Sending and Mail Configuration
Database reference
- 67MySQLi vs. PDO
- 68Connecting PHP to MySQL
- 69Creating Databases and Tables with PHP
- 70Insert, Select, Update and Delete with MySQLi
- 71Prepared Statements with MySQLi
- 72Last Insert ID and Multiple Inserts
- 73Transactions with PDO
- 74Database Error Handling
- 75Pagination and Search with SQL
- 76PHP Database Connection Best Practices
Professional PHP
- 77PHP Configuration and php.ini
- 78Error Reporting and Logging
- 79Composer Dependencies and Version Constraints
- 80PSR Standards and Autoloading
- 81Environment Variables and .env Configuration
- 82Unit Testing with PHPUnit
- 83PHP Performance and OPcache Basics
- 84Deployment and Production Configuration
- 85PHP Security Checklist
- 86PHP Interview Questions and Coding Exercises