PhPHP · Lesson 8 of 8
PHP Cheatsheet
Modern PHP 8 syntax, arrays, and classes on one page.
PHP
<?php
declare(strict_types=1); // top of every file
// ── Basics ──────────────────────────────
$x = 42;
$name = "Ada";
echo "Hi $name"; // "..." interpolates
echo 'literal $name'; // '...' doesn't
$s = $a . $b; // concatenation
var_dump($x); // debug print
// ── Comparisons — use === always ────────
$a === $b; $a !== $b; // value AND type
$x ?? "default"; // null coalescing
$obj?->method(); // nullsafe
$cond ? "yes" : "no";
// ── Control flow ────────────────────────
if ($x > 10) { } elseif ($x > 5) { } else { }
foreach ($items as $item) { }
foreach ($map as $key => $value) { }
for ($i = 0; $i < 5; $i++) { }
while ($cond) { }
$label = match(true) {
$x >= 90 => "A",
$x >= 80 => "B",
default => "C",
};
// ── Functions ───────────────────────────
function greet(string $name, int $times = 1): string {
return str_repeat("Hi $name! ", $times);
}
greet("Ada", times: 3); // named args
$double = fn($n) => $n * 2; // arrow fn (auto-capture)PHP
<?php
// ── Arrays ──────────────────────────────
$nums = [3, 1, 4];
$nums[] = 1; // append
count($nums); in_array(4, $nums); sort($nums);
$student = ["name" => "Ada", "age" => 17];
$student["email"] = "a@b.c";
array_map(fn($n) => $n * 2, $nums);
array_filter($nums, fn($n) => $n > 1);
array_reduce($nums, fn($c, $n) => $c + $n, 0);
array_keys($m); array_values($m); array_merge($a, $b);
implode(", ", $nums); explode(",", $csv);
array_slice($nums, 0, 2); array_sum($nums);
// ── Strings ─────────────────────────────
strlen($s); strtoupper($s); trim($s);
str_contains($s, "x"); str_starts_with($s, "ph");
str_replace("a", "b", $s); substr($s, 0, 5);
sprintf("%s: %d", $name, $x);
// ── Classes (PHP 8) ─────────────────────
class Student {
public function __construct(
public readonly string $name, // promoted props
private int $grade = 0,
) {}
public function grade(): int { return $this->grade; }
}
$s = new Student("Ada", 95);
echo $s->name;
enum Status: string {
case Active = 'active';
case Banned = 'banned';
}
// ── Web & DB essentials ─────────────────
$_GET['q'] ?? ''; $_POST['name'] ?? '';
htmlspecialchars($input); // ALWAYS escape output
$pdo = new PDO('sqlite:app.db');
$st = $pdo->prepare('SELECT * FROM users WHERE id = ?');
$st->execute([$id]); // NEVER concat SQL
json_encode($data); json_decode($json, true);
// php -S localhost:8000 | composer require pkg