PHP Cheat Sheet
Basics
// output and variables
echo "Hi $name\n"; printf("%05.2f", $x); print_r($arr); var_dump($x);
$n = (int) "42"; $s = (string) 5; $f = floatval("2.5");
define("MAX", 10); const MIN = 1;
Strings
strlen($s); strtoupper($s); strtolower($s); ucfirst($s); trim($s);
str_contains($s, "a"); str_replace("a", "b", $s); substr($s, 0, 3);
explode(",", $s); implode(",", $arr); strrev($s); sprintf("%d items", $n);
Arrays
$a = [1, 2]; $a[] = 3; count($a); in_array(2, $a); array_search(2, $a);
$m = ["k" => "v"]; array_keys($m); array_values($m); isset($m["k"]);
sort($a); rsort($a); asort($m); ksort($m); usort($a, fn($x, $y) => $x <=> $y);
array_map($f, $a); array_filter($a, $f); array_reduce($a, $f, 0);
array_merge($a, $b); array_slice($a, 1, 2); array_unique($a);
Control flow
if ($a) { } elseif ($b) { } else { }
foreach ($arr as $key => $value) { }
for ($i = 0; $i < 10; $i++) { }
$label = match ($code) { 200 => "ok", 404 => "missing", default => "other" };
Functions and classes
function add(int $a, int $b = 0): int { return $a + $b; }
$sq = fn($x) => $x * $x;
class User { public function __construct(public string $name) {} }
$u = new User("Asha"); echo $u->name;
Web
$_GET["q"]; $_POST["email"]; $_SERVER["REQUEST_METHOD"];
session_start(); $_SESSION["id"] = 1; setcookie("k", "v", time() + 3600);
header("Location: /login.php"); exit;
htmlspecialchars($input); json_encode($data); json_decode($json, true);
password_hash($p, PASSWORD_DEFAULT); password_verify($p, $hash);
PDO
$pdo = new PDO($dsn, $user, $pass);
$st = $pdo->prepare("SELECT * FROM t WHERE id = ?"); $st->execute([$id]);
$rows = $st->fetchAll(PDO::FETCH_ASSOC);
Full PHP documentation