Skip to content
AgileLogics

PHP Cheat Sheet

Learn PHP from the basics →

Variables

$name = "value";
Declare a variable
"Hello, $name"
String interpolation (double quotes only)
gettype($x)
Get a variable's type

Arrays

[1, 2, 3]
Indexed array
["k" => "v"]
Associative array
count($arr)
Array length
array_map($fn, $arr)
Transform each element
array_filter($arr, $fn)
Keep matching elements

Strings

strlen($s)
String length
strtolower($s) / strtoupper($s)
Change case
str_contains($s, $needle)
Check for a substring
trim($s)
Remove surrounding whitespace
explode(",", $s)
Split into an array

Control Flow

if / elseif / else
Conditional branching
foreach ($arr as $k => $v)
Loop with key and value
match ($x) { 1 => "one", default => "?" }
PHP 8 match expression

Functions

function f(string $x): string { }
Typed function
fn ($x) => $x * 2
Arrow function
f(name: "Ada")
Named argument

Classes

class User { public function __construct(public string $name) {} }
Constructor property promotion
new User("Ada")
Instantiate
$user->name
Access a property
interface Payable { public function pay(): void; }
Interface
enum Status { case Active; case Inactive; }
Enum (PHP 8.1+)

Errors & Database

try { } catch (Exception $e) { }
Exception handling
new PDO($dsn, $user, $pass)
Connect to a database
$stmt = $pdo->prepare("... WHERE id = ?"); $stmt->execute([$id]);
Parameterized query