PHPPrintable

PHP Cheat Sheet

Output, strings, arrays, functions, forms, sessions, dates, regex, files, JSON, PDO, OOP, Composer, passwords, security and APIs on one printable page.

Back to the PHP tutorial

Tags, variables & strings

SyntaxWhat it doesLesson
<?php ... ?> <?= $x ?>Code block / print a valueIntroduction
php -S localhost:8000Start a local serverIntroduction
$name = "Ana";Create a variableVariables
"Hi $name" 'Hi ' . $nameInterpolate / joinVariables
strlen() strtoupper() trim() str_replace()String helpersVariables

Conditions, loops & arrays

SyntaxWhat it doesLesson
=== !== ??Strict compare / fallbackif/else
match ($v) { 1 => "a", default => "b" }Pick a valueif/else
foreach ($a as $k => $v) { }Loop keys and valuesLoops
$a[] = "x"; count($a)Add, countArrays
in_array() sort() asort() implode() explode()Array functionsArrays

Functions & includes

SyntaxWhat it doesLesson
function f(int $x = 1): string { }Typed function with defaultFunctions
f(name: "Ana")Named argumentFunctions
require __DIR__ . '/header.php';Include a required fileinclude
require_once 'functions.php';Load only onceinclude

Forms & validation

SyntaxWhat it doesLesson
$_GET['q'] ?? '' $_POST['email'] ?? ''Read form valuesForms
$_SERVER['REQUEST_METHOD'] === 'POST'Was the form submitted?Forms
htmlspecialchars($s)Escape output (prevent XSS)Forms
header('Location: thanks.php'); exit;Redirect after POSTForms
filter_var($e, FILTER_VALIDATE_EMAIL)Validate an emailValidation
hash_equals($_SESSION['token'], $t)Check a CSRF tokenValidation

Sessions, cookies & files

SyntaxWhat it doesLesson
session_start(); $_SESSION['id'] = 5;Remember data on the serverSessions
session_destroy();Log outSessions
setcookie('theme', 'dark', [...]); $_COOKIE['theme']Set / read a cookieSessions
file_get_contents($p) file_put_contents($p, $s, FILE_APPEND)Read / write filesFiles
fgetcsv($handle)Read a CSV rowFiles
move_uploaded_file($tmp, $dest)Save an uploadFiles

JSON & databases

SyntaxWhat it doesLesson
json_encode($data, JSON_PRETTY_PRINT)PHP to JSONJSON
json_decode($json, true)JSON to arrayJSON
header('Content-Type: application/json');Return JSONJSON
new PDO($dsn, $user, $pass, [...])Connect to a databasePDO
$s = $pdo->prepare('... WHERE id = ?'); $s->execute([$id]);Prepared statementPDO
$s->fetchAll() $pdo->lastInsertId()Read rows / new idPDO

Classes & exceptions

SyntaxWhat it doesLesson
class P { public function __construct(private string $n) {} }Class with promoted propertyClasses
$p = new P('x'); $p->method();Create and use an objectClasses
class B extends A parent::method()InheritanceClasses
interface I { } class C implements IContractsClasses
try { } catch (Exception $e) { } finally { }Handle errorsExceptions
throw new InvalidArgumentException('msg');Report a problemExceptions

Strings & array functions

SyntaxWhat it doesLesson
trim($s) strtolower($s) ucwords($s)Tidy textString Functions
str_contains($s, "x") strpos($s, "x") === falseSearch textString Functions
substr($s, 0, 10) mb_strlen($s)Part of a string, real lengthString Functions
sprintf("%s: £%.2f", $n, $p) number_format($n, 2)Format valuesString Functions
array_map(fn($x) => $x * 2, $a)Transform every itemArray Functions
array_filter($a, fn($x) => $x > 0)Keep matching itemsArray Functions
usort($a, fn($x, $y) => $x['p'] <=> $y['p'])Sort recordsArray Functions
array_column($rows, 'name', 'id')Pull out a fieldArray Functions

Dates & regex

SyntaxWhat it doesLesson
date('Y-m-d H:i:s')Current date and timeDates & Times
new DateTimeImmutable('2024-07-05')Create a dateDates & Times
$d->modify('+3 days') $a->diff($b)->daysMove a date, days betweenDates & Times
preg_match('/^[a-z]{3,15}$/i', $s)Validate by patternRegular Expressions
preg_match_all('/#(\w+)/', $s, $m)Find every matchRegular Expressions
preg_replace('/\s+/', ' ', $s)Replace by patternRegular Expressions

OOP & Composer

SyntaxWhat it doesLesson
abstract class Shape { abstract public function area(): float; }Abstract classInterfaces, Traits & Enums
class Card implements PaymentMethodImplement an interfaceInterfaces, Traits & Enums
trait Loggable { } and use Loggable;Share methodsInterfaces, Traits & Enums
enum Status: string { case Paid = 'paid'; }Fixed set of valuesInterfaces, Traits & Enums
namespace App\Models; use App\Models\User;NamespacesNamespaces & Composer
composer require vendor/packageInstall a packageNamespaces & Composer
require __DIR__ . '/vendor/autoload.php';Autoload classesNamespaces & Composer

Apps, security & APIs

SyntaxWhat it doesLesson
header('Location: index.php'); exit;Redirect after POSTCRUD App
password_hash($p, PASSWORD_DEFAULT)Hash a passwordLogin & Passwords
password_verify($typed, $hash)Check a passwordLogin & Passwords
session_regenerate_id(true)New session id at loginLogin & Passwords
htmlspecialchars($s, ENT_QUOTES, 'UTF-8')Escape output (XSS)Web Security
hash_equals($_SESSION['csrf'], $_POST['csrf'])Check a CSRF tokenWeb Security
json_decode(file_get_contents('php://input'), true)Read a JSON requestREST API
http_response_code(201)Set the status codeREST 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" == 0 was 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 use str_contains in 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() and header() 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