PHP Cheat Sheet
Modern PHP reference with arrays, OOP, PHP 8.x features, string functions, and common patterns. Copy-ready code examples.
Variables
| Syntax | Description | Example |
|---|---|---|
| Variable assignment (dollar sign prefix) | $name = 'Alice'; | |
| Output to browser/console | echo 'Hello World'; | |
| Dump variable type and value | var_dump($arr); // array(3) {...} | |
| Check if variable is set and not null | if (isset($name)) { ... } | |
| Check if variable is empty/falsy | if (empty($input)) { ... } | |
| Destroy a variable | unset($temp); | |
| Get the type as a string | gettype(42) → 'integer' | |
| Type casting | (int) '42' → 42 | |
| Define a constant | define('PI', 3.14159); | |
| Class/namespace constant | const MAX_SIZE = 100; |
Strings
| Syntax | Description | Example |
|---|---|---|
| String length | strlen('hello') → 5 | |
| Change case | strtoupper('hello') → 'HELLO' | |
| Remove whitespace from both ends | trim(' hi ') → 'hi' | |
| Split string into array | explode(',', 'a,b,c') → ['a','b','c'] | |
| Join array into string | implode(', ', ['a','b']) → 'a, b' | |
| Replace occurrences | str_replace('l','r','hello') → 'herro' | |
| Extract substring | substr('hello', 1, 3) → 'ell' | |
| Find position of substring | strpos('hello', 'll') → 2 | |
| Formatted string | sprintf('%.2f', 3.14159) → '3.14' | |
| Variable interpolation (double quotes) | "Age: {$user->age}" | |
| Check if string contains substring (8.0+) | str_contains('hello', 'ell') → true | |
| Check start/end of string (8.0+) | str_starts_with('hello', 'he') → true |
Arrays
| Syntax | Description | Example |
|---|---|---|
| Create an indexed array | $fruits = ['apple', 'banana']; | |
| Create an associative array | $user = ['name' => 'Alice', 'age' => 30]; | |
| Add to end of array | array_push($arr, 'new'); | |
| Remove and return last element | $last = array_pop($arr); | |
| Remove from / add to beginning | array_unshift($arr, 'first'); | |
| Number of elements | count([1,2,3]) → 3 | |
| Check if value exists in array | in_array('apple', $fruits) → true | |
| Check if key exists | array_key_exists('name', $user) | |
| Merge two or more arrays | array_merge([1,2], [3,4]) → [1,2,3,4] | |
| Apply callback to each element | array_map(fn($x) => $x*2, [1,2,3]) | |
| Filter elements by callback | array_filter([1,2,3], fn($x) => $x>1) | |
| Sort array (by value / assoc / key) | sort($arr); asort($assoc); | |
| Extract a portion of array | array_slice([1,2,3,4], 1, 2) → [2,3] | |
| Get all keys or values | array_keys($user) → ['name','age'] |
Control Flow
| Syntax | Description | Example |
|---|---|---|
| Conditional branching | if ($x > 0) { ... } elseif (...) { ... } | |
| Switch statement | switch ($day) { case 'Mon': ... break; } | |
| Match expression (8.0+) | match($status) { 200 => 'OK', 404 => 'Not Found' } | |
| For loop | for ($i=0; $i<10; $i++) { echo $i; } | |
| Foreach loop | foreach ($users as $user) { ... } | |
| Foreach with key and value | foreach ($user as $key => $val) { ... } | |
| While loop | while ($i < 10) { $i++; } | |
| Exception handling | try { ... } catch (Exception $e) { ... } | |
| Throw an exception | throw new \InvalidArgumentException('Bad input'); | |
| Elvis operator (shorthand ternary) | $name = $input ?: 'Anonymous'; | |
| Null coalescing operator | $name = $_GET['name'] ?? 'Guest'; |
Functions
| Syntax | Description | Example |
|---|---|---|
| Define a function | function add($a, $b) { return $a + $b; } | |
| Arrow function (8.0+) | array_map(fn($x) => $x*2, $arr) | |
| Anonymous function / closure | $greet = function($name) { return "Hi $name"; }; | |
| Type declarations | function add(int $a, int $b): int { ... } | |
| Nullable type | function find(?int $id): ?User { ... } | |
| Variadic parameters | function sum(int ...$nums) { return array_sum($nums); } | |
| Return from function | return $result; |
OOP
| Syntax | Description | Example |
|---|---|---|
| Define a class | class User { public string $name; } | |
| Instantiate a class | $user = new User('Alice'); | |
| Access instance property/method | $this->name = $name; | |
| Visibility modifiers | private string $email; | |
| Inheritance / interface implementation | class Admin extends User implements Loggable | |
| Abstract classes and interfaces | interface Cacheable { public function cache(): void; } | |
| Traits (horizontal reuse) | trait Timestamps { ... } class Post { use Timestamps; } | |
| Static methods and properties | User::find(1); static::$count++; | |
| Read-only properties (8.1+) | public readonly string $id; | |
| Enums (8.1+) | enum Color: string { case Red = 'red'; } |
Modern PHP
| Syntax | Description | Example |
|---|---|---|
| Nullsafe operator (8.0+) | $user?->address?->city | |
| Named function arguments (8.0+) | str_contains(haystack: $s, needle: 'x') | |
| Constructor property promotion (8.0+) | public function __construct(private string $name) {} | |
| Union type declarations (8.0+) | function parse(string|int $input): array|false | |
| Intersection types (8.1+) | function process(Countable&Iterator $items) | |
| Lightweight concurrency (8.1+) | $fiber = new Fiber(function() { Fiber::suspend('hi'); }); |
Frequently asked questions
Is PHP still relevant in 2024?
Absolutely. PHP powers ~77% of websites with known server-side languages, including WordPress, Laravel, and Symfony. PHP 8.x has modern features like JIT compilation, fibers, enums, and union types that make it competitive with any modern language.
What's the difference between == and === in PHP?
== performs loose comparison with type juggling ('0' == false is true). === performs strict comparison checking both value AND type ('0' === false is false). Always use === unless you explicitly need type coercion.
Should I use PHP frameworks?
For production apps, yes. Laravel is the most popular, offering routing, ORM, authentication, queues, and more. Symfony is great for enterprise. For small scripts or APIs, plain PHP with Composer is fine.
How do I handle errors in PHP?
Use try/catch for exceptions, set_error_handler() for legacy errors, and set error_reporting(E_ALL) in development. In production, log errors instead of displaying them. Modern frameworks handle this automatically.
What's the difference between include and require?
Both include other PHP files. 'require' produces a fatal error if the file is missing; 'include' only produces a warning. Use require_once / include_once to prevent double-loading. In modern PHP, use Composer autoloading instead.
How does PHP compare to Node.js?
PHP excels at traditional web apps with its request-response model and vast ecosystem (WordPress, Laravel). Node.js is better for real-time apps, microservices, and when you want the same language on frontend and backend. Many teams use both.
Go from reference to real skills
Cheat sheets are great for quick lookups. Our in-depth courses take you from the fundamentals to professional-level mastery.
Browse all courses