PHP Cheat Sheet
Free PHP cheat sheet: syntax, arrays, OOP, database functions, and web essentials in one quick reference.
Basics
| Concept | Syntax | Example |
|---|---|---|
| Variable | $name = value; | $count = 0; |
| Constant | define('NAME', value) | define('PI', 3.14); |
echo / print | echo "Hello $name"; | |
| Array | $arr = [1, 2, 3] | $fruits = ['apple', 'banana']; |
| Type casting | (int), (string), (array) | $num = (int) "42"; // 42 |
Strings
| Concept | Syntax | Example |
|---|---|---|
| Concatenate | $a . $b | $full = $first . ' ' . $last; |
| Interpolation | "Hello $name" | echo "Age: $age"; |
| Functions | strlen, strtoupper, substr | echo strlen('hello'); // 5 |
| Regex | preg_match, preg_replace | preg_match('/\d+/', $str, $m); |
OOP
| Concept | Syntax | Example |
|---|---|---|
| Class | class Name { } | class Dog { public $name; } |
| Constructor | __construct(params) | function __construct(public string $name) {} |
| Inheritance | class B extends A { } | class Puppy extends Dog {} |
| Interface | interface Name { } | interface Drawable { public function draw(); } |
Arrays
| Concept | Syntax | Example |
|---|---|---|
| Associative | ['key' => 'val'] | $user = ['name' => 'Alice']; |
| Functions | array_map, array_filter, array_merge | array_map(fn($x) => $x*2, $arr); |
| Sorting | sort, asort, ksort | sort($numbers); |
Database (PDO)
| Concept | Syntax | Example |
|---|---|---|
| Connect | new PDO(dsn, user, pass) | $pdo = new PDO('mysql:host=localhost;dbname=app', 'root', ''); |
| Prepared stmt | $pdo->prepare(sql) | $stmt = $pdo->prepare('SELECT * FROM users WHERE id = ?'); |
| Execute | $stmt->execute([vals]) | $stmt->execute([1]); $row = $stmt->fetch(); |