Skip to content
Tutorials Center
My learning

Topics

Lesson 139 of 147 ยท Practice and Review

PHP Cheat Sheet

A dense one-page PHP 8.5 reference: syntax, types, strings, arrays, functions, OOP, enums, errors, files, JSON, PDO, security and new features by version.

This page squeezes the whole PHP course into one dense reference: the syntax, functions and idioms you reach for every day, in short snippets you can scan in seconds. Keep it open while you work through the practice exercises and the classic PHP programs, while you write your own code, or the evening before an interview.

Everything here is modern PHP 8.5, and features added after PHP 8.0 are labeled with the version that introduced them, so you know what works on an older server. Each section links to the lesson that explains the topic properly. The items that trip people up most come with live editors: run them and watch the behavior.

Basics

A script

PHP
<?php

declare(strict_types=1);          // first statement: scalar types are not coerced

namespace App;                    // optional; see Namespaces

use InvalidArgumentException;     // import a class

echo 'Hello, world!', PHP_EOL;    // echo takes several arguments
print "Hello\n";                  // print takes one and returns 1
printf("%s is %d\n", 'PHP', 30);  // formatted output
  • Files that contain only PHP omit the closing ?>, so no stray whitespace is sent after it.
  • Statements end with ;. Keywords, function names and class names are case-insensitive (ECHO works); variable names and constants are case-sensitive.
  • In templates, <?= $x ?> is short for <?php echo $x; ?>.
  • Run a file with php script.php; start a development server with php -S localhost:8000 -t public.

Lessons: Getting Started, How PHP Works, Syntax, Output.

Comments

PHP
// one line
# also one line
/* several
   lines */
/**
 * DocBlock: read by IDEs and static analysers.
 *
 * @param list<string> $names
 * @return array<string, int>
 */

Variables and constants

PHP
$name = 'Ada';                  // variables start with $, no declaration
$count = 3;
$name = 42;                     // a variable can change type (unless typed properties/params)

isset($x);                      // true if set and not null
empty($x);                      // true if unset or falsy ('', '0', 0, 0.0, [], null, false)
unset($x);                      // removes the variable

const MAX_ITEMS = 50;           // compile-time constant (top level or in a class)
define('APP_ENV', 'local');     // run-time constant, can be defined conditionally

PHP_EOL; PHP_INT_MAX; PHP_INT_SIZE; PHP_FLOAT_EPSILON; PHP_VERSION; PHP_OS_FAMILY; M_PI;
__LINE__; __FILE__; __DIR__; __FUNCTION__; __CLASS__; __METHOD__; __NAMESPACE__;

Reading an undefined variable gives Warning: Undefined variable $x and the value null. See Variables and Constants.

Types

Type Examples Notes
int 42, -7, 0x2A, 0o52 (8.1), 052, 0b101010, 1_000_000 64-bit on modern systems; overflows to float
float 3.14, 1.5e3, .5, 1_000.5 IEEE 754 double; never use for money
string 'single', "double $var" byte strings; see Strings
bool true, false case-insensitive keywords
array [1, 2], ['a' => 1] ordered map of int/string keys to values
object new Foo() instances of classes, stdClass, closures, enums
null null the only value of type null
callable, iterable, mixed pseudo-types for declarations
void, never (8.1), static return types only
PHP
gettype(1.0);              // 'double' (historical name)
get_debug_type(1.0);       // 'float'  (8.0; also gives class names)
var_dump($x);              // type and value, recursive
is_int($x); is_string($x); is_array($x); is_numeric('12.5'); is_callable($f); $x instanceof Foo;

(int) '12abc';             // 12          (int) 'abc' โ†’ 0     (int) 3.99 โ†’ 3
(float) '1.5e3';           // 1500.0
(string) 1.0;              // '1'         (string) false โ†’ '' (string) true โ†’ '1'
(bool) '0';                // false       (bool) '0.0' โ†’ true  (bool) [] โ†’ false
(array) 'x';               // ['x']
intdiv(7, 2);              // 3           7 % 2 โ†’ 1    7 / 2 โ†’ 3.5    fdiv(1, 0) โ†’ INF

Lessons: Data Types, Integers and Floats, Booleans and null, Type Juggling and Casting.

Comparisons: == vs ===

=== compares type and value and is almost always what you want. PHP 8 changed == between numbers and non-numeric strings: the number is converted to a string, not the other way around. Run this to see the rules:

PHP Loose and strict comparisons in PHP 8

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Use === and !== by default, and in_array($x, $list, true) / array_search($x, $list, true) with the strict flag. See Comparison Operators.

Operators

PHP
$a + $b; $a - $b; $a * $b; $a / $b; $a % $b; $a ** $b;   // arithmetic (% gives the sign of $a)
$s = 'Hello' . ' ' . 'world';  $s .= '!';               // concatenation
$n += 5; $n -= 1; $n *= 2; $n /= 4; $n **= 2; $n %= 3;  // compound assignment
$i++; ++$i; $i--; --$i;

$a == $b; $a === $b; $a != $b; $a !== $b; $a <=> $b;      // <=> returns -1, 0 or 1
$a && $b; $a || $b; !$a;                                   // use these, not and/or (lower precedence)

$x ?: 'default';               // $x if truthy, otherwise 'default'
$x ?? 'default';               // $x if set and not null (no warning if undefined)
$x ??= 'default';              // assign only if null/unset
$user?->address?->city;        // nullsafe (8.0): null instead of an error
$isAdult = $age >= 18 ? 'yes' : 'no';   // nested ternaries need parentheses

$flags = READ | WRITE; $flags & WRITE; $flags & ~WRITE; 1 << 3; $a ^ $b;   // bitwise
$merged = $defaults + $options;          // array union: keeps left keys
$obj instanceof Countable;
$result = $input |> trim(...) |> strtolower(...);   // pipe operator (8.5)

Precedence, highest first (simplified): clone new โ†’ ** โ†’ ++ -- ~ (casts) @ โ†’ instanceof โ†’ ! โ†’ * / % โ†’ + - โ†’ << >> โ†’ . โ†’ |> (8.5) โ†’ < <= > >= โ†’ == != === !== <=> โ†’ & โ†’ ^ โ†’ | โ†’ && โ†’ || โ†’ ?? โ†’ ? : โ†’ = += ... โ†’ and โ†’ xor โ†’ or. So 'a' . 'b' |> strtoupper(...) gives 'AB', and $s |> strlen(...) == 1 compares the length. When in doubt, add parentheses. Full table: Bitwise, String, Array and Pipe Operators. Lessons: Arithmetic, Logical Operators, Null Coalescing, Ternary and Nullsafe.

Control flow

PHP
if ($score >= 90) {
    $grade = 'A';
} elseif ($score >= 80) {
    $grade = 'B';
} else {
    $grade = 'C';
}

$label = match (true) {             // match (8.0): strict ===, returns a value, no fall-through
    $score >= 90 => 'excellent',
    $score >= 50 => 'pass',
    default => 'fail',              // without a matching arm: UnhandledMatchError
};

switch ($command) {                 // loose ==, falls through without break
    case 'start':
    case 'run':
        run();
        break;
    default:
        help();
}

while ($line = fgets($handle)) { /* ... */ }
do { $n--; } while ($n > 0);
for ($i = 0; $i < 10; $i++) { /* ... */ }
foreach ($items as $item) { /* ... */ }
foreach ($prices as $sku => $price) { /* ... */ }
foreach ($rows as ['id' => $id, 'name' => $name]) { /* ... */ }   // destructuring
foreach ($numbers as &$n) { $n *= 2; } unset($n);                // by reference: unset after!

break; continue; break 2; continue 2;   // the number says how many loops to leave

Template syntax: if (...): ... elseif (...): ... else: ... endif;, foreach (...): ... endforeach;, also endwhile, endfor and endswitch. Lessons: if and else, switch and match, Loops, foreach, break and continue.

Strings

PHP
'No $interpolation, only \' and \\ escapes';
"Interpolates $name and {$user->name} and {$items['key']}, escapes \n \t \u{1F600}";

$html = <<<HTML
    <p>Hello, {$name}!</p>      // heredoc: like double quotes; closing marker sets indentation
    HTML;
$raw = <<<'TEXT'
    No $interpolation here      // nowdoc: like single quotes
    TEXT;

$s[0]; $s[-1];                  // first and last byte
Task Function
length in bytes / characters strlen($s) / mb_strlen($s)
contains, starts, ends (8.0) str_contains($s, 'x'), str_starts_with, str_ends_with
position strpos($s, 'x') (returns false if absent: compare with !== false), stripos, strrpos
part of a string substr($s, 0, 5), mb_substr($s, -3)
replace str_replace('a', 'b', $s), str_ireplace, substr_replace, strtr($s, ['a' => 'b'])
trim trim($s), ltrim, rtrim, trim($s, '/'), mb_trim (8.4)
case strtolower, strtoupper, ucfirst, lcfirst, ucwords, mb_strtolower, mb_ucfirst (8.4)
pad, repeat, reverse str_pad($s, 10, '-', STR_PAD_LEFT), mb_str_pad (8.3), str_repeat('=', 20), strrev
split and join explode(',', $s), implode(', ', $list), str_split($s, 3), mb_str_split
format sprintf('%05.2f', $x), number_format(1234.5, 2) โ†’ '1,234.50'
compare strcmp, strcasecmp, strncmp, strnatcmp
HTML htmlspecialchars($s), strip_tags, nl2br
wrap wordwrap($s, 40, "\n", true)

sprintf specifiers: %s string, %d integer, %f / %.2f float, %e scientific, %x / %X hex, %o octal, %b binary, %c character, %% a percent sign, %'*10s custom padding, %-10s left-align, %+d always a sign, %1$s argument number.

PHP
preg_match('/(\d{4})-(\d{2})/', $date, $m);           // 1 if found; $m[1], $m[2]
preg_match('/(?<year>\d{4})/', $date, $m);            // $m['year']
preg_match_all('/\d+/', $text, $m);                   // all matches in $m[0]
preg_replace('/\s+/', ' ', $text);
preg_replace_callback('/\d+/', fn ($m) => $m[0] * 2, $text);
preg_split('/[\s,]+/', $text, -1, PREG_SPLIT_NO_EMPTY);
preg_quote($userInput, '/');                          // escape for use inside a pattern
// flags: i (case), m (multiline ^$), s (dot matches \n), u (UTF-8), x (extended)

Lessons: Strings, String Functions, Unicode and Multibyte Strings, Formatting Strings, Regular Expressions.

Arrays

PHP
$list = ['red', 'green'];               // keys 0, 1
$list[] = 'blue';                       // append
$map = ['id' => 7, 'name' => 'Ada'];    // associative
$map['email'] = '[email protected]';
$grid = [[1, 2], [3, 4]];  $grid[1][0]; // 3
count($list);
isset($map['id']);                      // false if the value is null
array_key_exists('id', $map);           // true even if the value is null
$map['missing'] ?? 'default';

[$first, $second] = $list;              // destructuring
['id' => $id, 'name' => $name] = $map;
[$a, $b] = [$b, $a];                    // swap
$all = [...$list, ...$more];            // spread (string keys since 8.1)

Keys: '8' becomes 8, true becomes 1, 1.7 becomes 1 (deprecated), null becomes '' (deprecated in 8.5).

Task Function
add / remove at end $a[] = $x, array_push, array_pop
add / remove at start array_unshift, array_shift
slice, splice array_slice($a, 1, 2), array_splice($a, 1, 2, ['x'])
merge array_merge($a, $b) (renumbers int keys, later string keys win), $a + $b
search in_array($x, $a, true), array_search($x, $a, true), array_find (8.4), array_find_key (8.4)
keys and values array_keys, array_values, array_flip, array_combine($keys, $values)
one column array_column($rows, 'name'), array_column($rows, 'name', 'id')
unique, count values array_unique, array_count_values
create range(1, 10), range('a', 'e'), array_fill(0, 3, ''), array_fill_keys
first and last array_first, array_last (8.5), array_key_first, array_key_last (7.3)
set operations array_diff, array_intersect, array_diff_key, array_intersect_key
check array_is_list (8.1), array_any, array_all (8.4)
transform array_map, array_filter, array_reduce, array_walk, array_sum, array_product
chunks array_chunk($a, 3), array_pad

Sorting

Function Sorts by Keeps keys?
sort / rsort value, ascending / descending no
asort / arsort value yes
ksort / krsort key yes
usort($a, fn ($x, $y) => $x['age'] <=> $y['age']) your comparison no
uasort / uksort your comparison on values / keys yes
natsort, natcasesort "natural" order (img2 before img10) yes

All sort functions sort in place and return true. Sorting is stable since PHP 8.0. Multi-key sort: fn ($x, $y) => [$x['last'], $x['first']] <=> [$y['last'], $y['first']].

PHP Map, filter, reduce and friends

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Lessons: Arrays, Associative Arrays, Multidimensional Arrays, Array Functions, Sorting Arrays, array_map, array_filter and array_reduce, Destructuring and Spread.

Functions

PHP
function greet(string $name, string $greeting = 'Hello'): string
{
    return "$greeting, $name!";
}
greet('Ada');                               // 'Hello, Ada!'
greet(greeting: 'Hi', name: 'Ada');         // named arguments (8.0)

function sum(int ...$numbers): int { return array_sum($numbers); }   // variadic
sum(1, 2, 3); sum(...[1, 2, 3]);            // argument unpacking

function addTax(float &$price): void { $price *= 1.2; }              // by reference

function find(int $id): ?User { /* ... */ }                // nullable: User or null
function parse(int|string $v): int|float { /* ... */ }     // union types (8.0)
function save(Countable&Iterator $c): void { /* ... */ }   // intersection (8.1)
function load((A&B)|null $x): void { /* ... */ }           // DNF types (8.2)
function fail(string $m): never { throw new RuntimeException($m); }   // never (8.1)

function counter(): int { static $n = 0; return ++$n; }    // static: keeps its value between calls

$double = function (int $n) use ($factor): int { return $n * $factor; };  // closure, captures by value
$add = function () use (&$total) { $total++; };            // capture by reference
$triple = fn (int $n): int => $n * $factor;                // arrow fn: captures automatically
$len = strlen(...);                                         // first-class callable (8.1)
$method = $object->method(...);  $static = Foo::create(...);

With declare(strict_types=1), passing '5' to an int parameter throws a TypeError; without it, PHP converts the value. The declaration affects calls made from that file. Lessons: Functions, Parameters and Arguments, Type Declarations, Variable Scope, Anonymous Functions and Closures, Recursion, Built-in Functions.

Object-oriented PHP

PHP
final class Product extends Model implements JsonSerializable, Stringable
{
    use HasTimestamps;                                   // trait

    public const string TABLE = 'products';             // typed constant (8.3)
    private static int $instances = 0;

    public function __construct(
        public readonly string $sku,                     // promotion (8.0) + readonly (8.1)
        private int $price = 0,
        protected array $tags = [],
    ) {
        parent::__construct();
        self::$instances++;
    }

    public static function fromArray(array $data): static   // named constructor
    {
        return new static($data['sku'], $data['price']);
    }

    #[\Override]                                         // 8.3: error if nothing is overridden
    public function jsonSerialize(): array { return ['sku' => $this->sku, 'price' => $this->price]; }

    public function __toString(): string { return $this->sku; }
}

$p = new Product('MUG-01', 1450);
$p->sku;  Product::TABLE;  Product::fromArray([...]);  $p::class;  // 'Product'
new Product('X')->jsonSerialize();                       // no extra parentheses needed (8.4)
$copy = clone $p;                                        // shallow copy; __clone() runs on the copy
Feature Syntax
visibility public, protected, private; asymmetric public private(set) (8.4)
readonly readonly properties (8.1), readonly class (8.2)
property hooks (8.4) public string $name { get => ...; set => ...; }
abstract abstract class Shape { abstract public function area(): float; }
interface interface HasArea { public function area(): float; }, may declare constants and (8.4) properties
trait trait Greets { ... } + use Greets;; conflicts with insteadof / as
static static::create() (late static binding) vs self::create()
final final class, final public function, final public const (8.1)
clone with (8.5) clone($this, ['x' => 5])
first-class enum enum Status: string { case Active = 'active'; }
magic methods __construct, __destruct, __get, __set, __isset, __unset, __call, __callStatic, __toString, __invoke, __clone, __serialize, __unserialize
comparison == same class and equal properties, === same instance
PHP Modern classes: promotion, enums, hooks, clone with

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Lessons: OOP in PHP, Classes, Constructors, Inheritance, Abstract Classes and Interfaces, Traits, Static Members, Constants and Enums, Readonly and Immutability, Property Hooks, Magic Methods, Namespaces, Autoloading and Composer.

Namespaces and autoloading

PHP
namespace App\Models;                        // one per file, before any code

use App\Services\Mailer;                     // class
use App\Services\Mailer as AppMailer;        // alias
use function App\Support\slugify;            // function
use const App\Support\VERSION;               // constant

new \DateTimeImmutable();                    // leading \ = global namespace

spl_autoload_register(function (string $class): void {
    $file = __DIR__ . '/src/' . str_replace(['App\\', '\\'], ['', '/'], $class) . '.php';
    if (is_file($file)) {
        require $file;
    }
});
Terminal
composer init                      # create composer.json
composer require vendor/package    # install and add to composer.json
composer install --no-dev          # install exactly what composer.lock says (production)
composer dump-autoload             # regenerate vendor/autoload.php after changing "autoload"

PSR-4 in composer.json: "autoload": {"psr-4": {"App\\": "src/"}}, then require __DIR__ . '/vendor/autoload.php';.

Errors and exceptions

PHP
try {
    $data = json_decode($json, flags: JSON_THROW_ON_ERROR);
} catch (JsonException | ValueError $e) {          // several types
    error_log($e->getMessage());
} catch (Exception) {                               // no variable needed (8.0)
    // ...
} finally {
    // always runs
}

$user = $repo->find($id) ?? throw new NotFoundException("User $id");   // throw expression (8.0)

final class NotFoundException extends RuntimeException {}
throw new DomainException('Invalid state', previous: $e);             // chain the cause
set_exception_handler(fn (Throwable $e) => error_log((string) $e));
set_error_handler(fn ($no, $msg, $file, $line) => throw new ErrorException($msg, 0, $no, $file, $line));
TEXT
Throwable
โ”œโ”€โ”€ Error              (engine problems: TypeError, ValueError, ArgumentCountError,
โ”‚                       ArithmeticError โ†’ DivisionByZeroError, UnhandledMatchError, ...)
โ””โ”€โ”€ Exception          (application problems)
    โ”œโ”€โ”€ LogicException   โ†’ InvalidArgumentException, DomainException, LengthException, OutOfRangeException
    โ”œโ”€โ”€ RuntimeException โ†’ OutOfBoundsException, UnexpectedValueException, RangeException, ...
    โ””โ”€โ”€ JsonException, PDOException, ...

Error levels: E_ERROR, E_WARNING, E_NOTICE, E_DEPRECATED, E_ALL. Development: error_reporting=E_ALL, display_errors=1. Production: display_errors=0, log_errors=1. Debugging: var_dump, print_r($x, true), var_export, debug_print_backtrace(), assert($x > 0). Lessons: Errors, Exceptions, Custom Exceptions, Debugging.

Files, JSON and other formats

PHP
$text = file_get_contents(__DIR__ . '/notes.txt');            // false on failure (plus a warning)
file_put_contents($path, $text);                              // returns bytes written or false
file_put_contents($path, "line\n", FILE_APPEND | LOCK_EX);
$lines = file($path, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

$handle = fopen($path, 'r');                                  // r, w, a, x, r+, w+ (add b on Windows)
while (($line = fgets($handle)) !== false) { /* ... */ }
fclose($handle);

is_file($p); is_dir($p); file_exists($p); filesize($p); filemtime($p); realpath($p);
mkdir($dir, 0775, true); scandir($dir); glob('*.txt'); unlink($p); rename($a, $b); copy($a, $b);
tempnam(sys_get_temp_dir(), 'tmp'); basename($p); dirname($p); pathinfo($p, PATHINFO_EXTENSION);

$csv = fopen('data.csv', 'r');
$header = fgetcsv($csv, escape: '');                          // omitting $escape is deprecated since 8.4
while (($row = fgetcsv($csv, escape: '')) !== false) { $records[] = array_combine($header, $row); }
fputcsv($out, ['id', 'name'], escape: '');
str_getcsv('a,"b,c",d', escape: '');                          // ['a', 'b,c', 'd']

json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR);
json_decode($json, true, flags: JSON_THROW_ON_ERROR);         // true: arrays instead of stdClass
json_validate($json);                                         // 8.3: check without decoding

$xml = simplexml_load_string($string);  $xml->book[0]->title;
$doc = Dom\HTMLDocument::createFromString($html, LIBXML_NOERROR);   // 8.4: HTML5 parser
$doc->querySelectorAll('a[href]');

$stdin = stream_get_contents(STDIN);                          // php://stdin, php://memory, php://temp, php://input

Lessons: Files, Directories, CSV, JSON, XML, Streams.

PHP and the web

PHP
$_GET['page'];  $_POST['email'];  $_FILES['photo'];  $_COOKIE['theme'];  $_SESSION['user_id'];
$_SERVER['REQUEST_METHOD'];  $_SERVER['REQUEST_URI'];  $_SERVER['HTTP_HOST'];  $_SERVER['REMOTE_ADDR'];
file_get_contents('php://input');                       // raw body (JSON APIs)

$email = filter_var($_POST['email'] ?? '', FILTER_VALIDATE_EMAIL);           // string or false
$page = filter_var($_GET['page'] ?? 1, FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);
echo htmlspecialchars($value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');        // ALWAYS escape output

http_response_code(404);
header('Content-Type: application/json');
header('Location: /thanks', true, 303);  exit;          // headers before any output
setcookie('theme', 'dark', ['expires' => time() + 86400 * 30, 'path' => '/',
    'secure' => true, 'httponly' => true, 'samesite' => 'Lax']);
session_start();  session_regenerate_id(true);  $_SESSION = [];  session_destroy();

move_uploaded_file($_FILES['photo']['tmp_name'], $safeTarget);              // after checking error, size, type
(new finfo(FILEINFO_MIME_TYPE))->file($_FILES['photo']['tmp_name']);         // real type, not the client's

ob_start(); require 'view.php'; $html = ob_get_clean();                       // render a template to a string

Lessons: Templates, Superglobals, Forms, Form Validation, File Uploads, Cookies, Sessions, Headers and Redirects, Routing, JSON APIs.

Databases with PDO

PHP
$pdo = new PDO('mysql:host=127.0.0.1;dbname=shop;charset=utf8mb4', $user, $password, [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,         // the default since 8.0
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_EMULATE_PREPARES => false,
]);
$pdo = new PDO('sqlite:' . __DIR__ . '/app.sqlite');     // or 'sqlite::memory:'
$pdo = PDO::connect('sqlite::memory:');                  // 8.4: returns a Pdo\Sqlite subclass

$stmt = $pdo->prepare('SELECT * FROM users WHERE email = :email');
$stmt->execute(['email' => $email]);                     // NEVER concatenate input into SQL
$user = $stmt->fetch();                                  // one row or false
$rows = $stmt->fetchAll();                               // all rows
$count = $pdo->query('SELECT COUNT(*) FROM users')->fetchColumn();
$pairs = $pdo->query('SELECT id, name FROM users')->fetchAll(PDO::FETCH_KEY_PAIR);

$pdo->prepare('INSERT INTO users (email) VALUES (?)')->execute([$email]);
$id = $pdo->lastInsertId();                              // a string
$stmt->rowCount();                                       // rows changed by INSERT/UPDATE/DELETE
$stmt->bindValue('limit', 10, PDO::PARAM_INT);

$pdo->beginTransaction();
try {
    // several statements...
    $pdo->commit();
} catch (Throwable $e) {
    $pdo->rollBack();
    throw $e;
}

$in = implode(',', array_fill(0, count($ids), '?'));     // IN list with placeholders
$pdo->prepare("SELECT * FROM users WHERE id IN ($in)")->execute($ids);

Placeholders hold values only; table names, columns and ORDER BY directions must come from a whitelist. Lessons: PHP and Databases, PDO Basics, Prepared Statements, CRUD, Transactions, MySQLi, Database Patterns.

PHP PDO with SQLite in memory

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Security essentials

Threat Defense
SQL injection prepared statements with placeholders; whitelist identifiers
XSS htmlspecialchars($s, ENT_QUOTES, 'UTF-8') on every output; Content-Security-Policy header
CSRF bin2hex(random_bytes(32)) token in the session and form, checked with hash_equals; SameSite cookies
password theft password_hash($pw, PASSWORD_DEFAULT), password_verify, password_needs_rehash; never md5/sha1
session hijacking session_regenerate_id(true) at login; HttpOnly, Secure, SameSite cookies; HTTPS
path traversal basename(), realpath() + prefix check; never pass input to include
command injection avoid shell calls; otherwise escapeshellarg() for every argument
unsafe deserialization never unserialize() user input; use json_decode
open redirects redirect only to local paths or a whitelist
information leaks display_errors=0, expose_php=Off in production; generic error pages
PHP
random_int(1, 6);                          // cryptographically secure integer
bin2hex(random_bytes(16));                 // 32 hex characters
hash('sha256', $data);  hash_hmac('sha256', $message, $secretKey);
hash_equals($known, $userValue);           // timing-safe comparison
$r = new Random\Randomizer();  $r->shuffleArray($cards);  $r->getBytesFromString('abc123', 8);  // 8.2 / 8.3
$nonce = random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
$box = sodium_crypto_secretbox($plain, $nonce, $key);    // authenticated encryption

Lessons: Web Security Basics, XSS, CSRF, Password Hashing, Cryptography, Secure Coding Checklist.

Dates and times

PHP
date('Y-m-d H:i:s');                         // now, in the default timezone
time();                                      // Unix timestamp
$d = new DateTimeImmutable('2026-03-15 14:30', new DateTimeZone('Europe/Berlin'));
$d->format('l, F j, Y \a\t g:i A');          // 'Sunday, March 15, 2026 at 2:30 PM'
$d->modify('+1 month');  $d->add(new DateInterval('P1DT2H'));  $d->setTime(0, 0);
$d->setTimezone(new DateTimeZone('UTC'));
DateTimeImmutable::createFromFormat('d/m/Y', '15/03/2026');   // false if it doesn't match
$a->diff($b)->days;  $a < $b;                // compare with operators
foreach (new DatePeriod($start, new DateInterval('P1W'), 4) as $day) { /* ... */ }

Format letters: Y 2026, m 03, d 05, j 5, D Thu, l Thursday, M Mar, F March, H 14, G 14, h 02, g 2, i minutes, s seconds, A PM, N weekday 1โ€“7, U timestamp, c ISO 8601. Store times in UTC and convert for display. See Dates and Times.

Advanced features

PHP
function readLines(string $path): Generator {          // generators: one value at a time
    $h = fopen($path, 'r');
    while (($line = fgets($h)) !== false) { yield rtrim($line, "\n"); }
    fclose($h);
}
yield $key => $value;  yield from otherGenerator();  $gen->send($x);

class Collection implements IteratorAggregate, Countable, ArrayAccess { /* ... */ }
new SplStack();  new SplQueue();  new SplObjectStorage();  new SplPriorityQueue();  new SplFixedArray(10);

#[Attribute(Attribute::TARGET_PROPERTY)]
final class Length { public function __construct(public int $max) {} }
(new ReflectionProperty(User::class, 'name'))->getAttributes(Length::class)[0]->newInstance()->max;

$fiber = new Fiber(function (): string { $x = Fiber::suspend('paused'); return "got $x"; });
$fiber->start();  $fiber->resume('data');  $fiber->getReturn();   // 8.1

$start = hrtime(true);  /* work */  $ms = (hrtime(true) - $start) / 1e6;
memory_get_usage();  memory_get_peak_usage();

$argv;  $argc;  getopt('v', ['name:']);  fwrite(STDERR, "error\n");  exit(1);   // command line

Lessons: Generators, Iterators and the SPL, Attributes, Reflection, Fibers, Type System, Performance, Command-Line PHP.

What's new, version by version

Version Headline features
8.0 (2020) named arguments, union types, match, nullsafe ?->, constructor promotion, attributes, str_contains/str_starts_with/str_ends_with, throw expressions, mixed, static return type, catch without variable, saner string-to-number comparisons, ::class on objects, JIT
8.1 (2021) enums, readonly properties, first-class callables f(...), new in initializers, intersection types, never, fibers, array_is_list, array unpacking with string keys, final class constants, 0o octal prefix
8.2 (2022) readonly classes, DNF types, null/false/true as types, the Random extension, constants in traits, #[\SensitiveParameter], dynamic properties deprecated
8.3 (2023) typed class constants, #[\Override], json_validate, dynamic class constant fetch Foo::{$name}, mb_str_pad, Randomizer::getBytesFromString, str_increment/str_decrement
8.4 (2024) property hooks, asymmetric visibility public private(set), new Foo()->bar() without parentheses, array_find/array_find_key/array_any/array_all, #[\Deprecated], lazy objects, Dom\HTMLDocument, PDO::connect and driver subclasses, BcMath\Number and bcround, new round() modes, mb_trim/mb_ucfirst, implicitly nullable parameters deprecated
8.5 (2025) pipe operator `
PHP PHP 8.5 in action: pipes, NoDiscard and the URI extension

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The addItem($cart, 'tea') line prints a warning on purpose: #[\NoDiscard] reports calls whose return value is thrown away, which catches bugs with functions like this one that return a new array instead of changing the old one. Uri::parse returns null for an invalid URI (the space in the host). Read What's New in PHP 8.0 to 8.5 for every feature with examples, and Deploying PHP Applications and Coding Standards for the production and style side.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does var_dump(0 == 'a'); print in PHP 8?

    Since PHP 8, comparing a number with a non-numeric string converts the number to a string, so "0" is compared with "a" and the result is false. In PHP 7 it was true.
  2. 2. Which function keeps the original keys when it removes elements?

    array_filter preserves keys, which can leave gaps like 0, 2, 3. Wrap it in array_values() if you need a list again.
  3. 3. What is the difference between $x ?? 'd' and $x ?: 'd'?

    With $x = 0, $x ?? 'd' gives 0 but $x ?: 'd' gives 'd'. Only ?? suppresses the undefined-variable warning.
  4. 4. Which PDO usage is safe against SQL injection?

    Prepared statements send the SQL and the values separately, so a value can never change the query. Escaping by hand is error-prone and not a substitute.
  5. 5. Which PHP version introduced property hooks and asymmetric visibility?

    Both arrived in PHP 8.4, together with new without parentheses and array_find/array_any/array_all. PHP 8.5 added the pipe operator and clone with.

Summary

  • Start every file with <?php and declare(strict_types=1);, omit the closing tag, and compare with ===.
  • Know the core string, array and sorting functions, and which ones keep keys or work on bytes rather than characters.
  • Use modern features freely: match, named arguments, constructor promotion, readonly, enums, first-class callables, property hooks (8.4) and the pipe operator (8.5).
  • Throw exceptions for errors, catch them where you can do something useful, and never show error details to users.
  • Escape output with htmlspecialchars, query with prepared statements, hash passwords with password_hash, and compare secrets with hash_equals.
  • Follow the links in each section when a one-line reminder isn't enough.

Next: PHP Programs: 50 Classic Examples