Quick Reference PHP Programming Cheatsheet
PHP 8 on one page — tags and CLI, types, operators, control flow, strings, arrays, functions,
OOP, exceptions, Composer, forms and sessions, files and JSON, PDO, and interview traps.
Built for revision and for looking things up while you code.
14 sections 13 tables 30 code snippets 🚀 Tags, Output & Running PHP Minimal script <?php
declare(strict_types=1);
echo "Hello, PHP!\n";
function main(): void {
$name = "Ravi";
echo "Hello, $name!\n";
}
main(); Run, built-in server, Composer php hello.php
php -v
php -l hello.php
php -S localhost:8000
php -r "echo 2 + 2;"
composer require vlucas/phpdotenv
composer dump-autoload echo, print, and HTML <?php
$name = "Ada";
echo "Hi ", $name, "\n";
print "one value only\n";
printf("Score: %03d\n", 7);
Put declare(strict_types=1); as the first statement in every file. It makes scalar type hints reject silent casts such as int parameters receiving "42". 🔢 Types, Variables & Casting Scalars and compounds <?php
declare(strict_types=1);
$n = 42;
$price = 19.5;
$ok = true;
$name = "Ada";
$items = [1, 2, 3];
$bag = null;
var_dump($n, $price, $ok, $name); Checks and casts <?php
is_int($n);
is_string($name);
is_array($items);
is_null($bag);
$age = (int) "21";
$flag = (bool) 1;
$text = (string) 42;
$copy = (array) $user; Variables always start with $. Names are case-sensitive. Function names are not. Prefer snake or the project’s style and stay consistent. ⚖️ Operators & Comparisons Everyday operators <?php
$sum = 2 + 3;
$mod = 7 % 3;
$label = $name ?? "guest";
$name ??= "guest";
$order = $a <=> $b;
$city = $user?->address?->city;
$ok = $age >= 18 && $age < 60; Compare on purpose <?php
0 == "0";
0 === "0";
0 == "foo";
null ?? "x";
false ?? "x";
isset($a) ? $a : "x"; if / elseif / else <?php
if ($score >= 90) {
$grade = "A";
} elseif ($score >= 80) {
$grade = "B";
} else {
$grade = "C";
} match (PHP 8) <?php
$label = match ($status) {
200, 201 => "ok",
404 => "missing",
500 => "server",
default => "other",
}; Loops <?php
for ($i = 0; $i < 3; $i++) {
echo $i;
}
foreach ($users as $id => $user) {
echo $user["name"];
}
while ($line = fgets($handle)) {
echo $line;
} Quotes and interpolation <?php
$name = "Ravi";
echo "Hello, $name";
echo 'Hello, $name';
echo "Line\nNext";
$path = __DIR__ . "/data.json";
$html = htmlspecialchars($name, ENT_QUOTES, "UTF-8"); Common string functions <?php
strlen("hi");
str_contains($hay, "php");
str_starts_with($url, "https");
str_ends_with($file, ".php");
trim(" hi ");
strtolower("PHP");
str_replace("php", "PHP", $s);
$parts = explode(",", "a,b,c");
$line = implode("-", ["a", "b"]);
sprintf("id=%04d", 7); Lists and maps <?php
$nums = [10, 20, 30];
$nums[] = 40;
$user = [
"name" => "Ravi",
"age" => 21,
];
$user["city"] = "Hyderabad";
echo $user["name"];
echo $nums[0]; Transform <?php
$doubled = array_map(fn($n) => $n * 2, $nums);
$adults = array_filter($users, fn($u) => $u["age"] >= 18);
$sum = array_reduce($nums, fn($carry, $n) => $carry + $n, 0);
$names = array_column($users, "name");
usort($users, fn($a, $b) => $a["age"] <=> $b["age"]); Typed function <?php
function greet(string $name, string $title = "Hi"): string {
return $title . ", " . $name;
}
echo greet("Ravi");
echo greet(name: "Ravi", title: "Hello"); Arrow, variadic, closure <?php
$add = fn(int $a, int $b): int => $a + $b;
function total(int ...$nums): int {
return array_sum($nums);
}
$prefix = "id";
$make = function (int $n) use ($prefix): string {
return $prefix . "-" . $n;
}; 🧱 Classes, Traits & Enums Constructor promotion <?php
class User {
public function __construct(
public readonly string $name,
private int $age,
) {}
public function greet(): string {
return "Hi, " . $this->name;
}
}
$u = new User("Ravi", 21); Interface, trait, enum <?php
interface Greeter {
public function greet(): string;
}
trait Timestamps {
public ?string $createdAt = null;
}
enum Status: string {
case Draft = "draft";
case Live = "live";
} try / catch / finally <?php
try {
if ($age < 0) {
throw new InvalidArgumentException("age must be >= 0");
}
} catch (InvalidArgumentException $e) {
error_log($e->getMessage());
} finally {
} Custom exception <?php
class NotFound extends RuntimeException {}
function findUser(int $id): User {
$user = $repo->find($id);
if ($user === null) {
throw new NotFound("user $id");
}
return $user;
} 📦 Namespaces, Includes & Composer Namespace and use <?php
namespace App\Models;
use App\Support\Str;
use PDO;
class Post {
public function slug(): string {
return Str::slug($this->title);
}
} Include vs autoload
{
"autoload": {
"psr-4": { "App\\": "src/" }
}
}
composer dump-autoload
🌐 Forms, Sessions & Cookies Read a form safely <?php
declare(strict_types=1);
$name = trim((string) ($_POST["name"] ?? ""));
$email = filter_input(INPUT_POST, "email", FILTER_VALIDATE_EMAIL);
if ($name === "" || $email === false) {
http_response_code(422);
exit("Invalid form");
} Session and cookie <?php
session_start();
$_SESSION["user_id"] = 15;
setcookie("theme", "dark", [
"expires" => time() + 60 * 60 * 24 * 30,
"path" => "/",
"httponly" => true,
"samesite" => "Lax",
"secure" => true,
]); Escape with htmlspecialchars on the way out to HTML. Validate on the way in. Never build SQL by concatenating $_POST values. Read and write <?php
$text = file_get_contents(__DIR__ . "/notes.txt");
file_put_contents(__DIR__ . "/out.txt", $text . "\n", FILE_APPEND);
$fh = fopen(__DIR__ . "/log.txt", "a");
if ($fh === false) {
throw new RuntimeException("cannot open log");
}
fwrite($fh, "ok\n");
fclose($fh); JSON <?php
$json = json_encode(["ok" => true], JSON_THROW_ON_ERROR);
$data = json_decode($json, true, 512, JSON_THROW_ON_ERROR);
if (!is_array($data) || !isset($data["ok"])) {
throw new RuntimeException("unexpected JSON");
} json_decode($json, true) returns associative arrays. Without true you get stdClass objects. JSON_THROW_ON_ERROR turns bad JSON into an exception instead of null. Connect and query <?php
$pdo = new PDO(
"mysql:host=localhost;dbname=app;charset=utf8mb4",
$user,
$pass,
[
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
],
);
$stmt = $pdo->prepare("SELECT id, name FROM users WHERE id = ?");
$stmt->execute([$id]);
$row = $stmt->fetch(); Insert with named placeholders <?php
$stmt = $pdo->prepare(
"INSERT INTO users (name, email) VALUES (:name, :email)"
);
$stmt->execute([
"name" => $name,
"email" => $email,
]);
$newId = (int) $pdo->lastInsertId(); Reference leftover <?php
$nums = [1, 2, 3];
foreach ($nums as &$n) {
$n *= 2;
}
unset($n);
foreach ($nums as $n) {
echo $n;
} Loose empty check <?php
empty("0");
empty(0);
empty("00");
$value = "0";
$missing = ($value === "" || $value === null); How to use this page: skim the jump chips, drill the tables, then type every snippet in php -a or a small file. Pair forms and PDO with a real request so the superglobals are not abstract. |