PHP Coding Cheat Sheet
PHP is one of the most popular server-side scripting languages for building dynamic and interactive web applications. Its simplicity and flexibility have made it a favourite among both beginners and seasoned developers. This cheat sheet provides a quick reference to essential PHP concepts—from basic syntax and variable handling to advanced topics like object-oriented programming and error management—allowing you to code more efficiently and debug faster. Whether you’re just starting out or looking to polish your skills, this guide offers clear, concise examples and practical tips to help you master PHP.
Designed as a comprehensive, printable resource, this PHP Coding Cheat Sheet is an indispensable tool for web developers. It covers a wide range of topics, including loops, conditional statements, arrays, functions, file inclusion, and database interactions with PDO. With detailed explanations and real-world examples, the cheat sheet simplifies complex concepts and ensures that you have a reliable reference at your fingertips. Download, print, and keep this guide nearby as you build, maintain, and improve your web projects.
Concept | Syntax/Example | Notes |
---|---|---|
PHP Opening & Closing Tags |
<?php // Your PHP code here ?> |
Indicates the start and end of a PHP script |
Echo Statement | echo "Hello, World!"; | Outputs text to the browser |
Variables | $variable = value; | Variables start with a $; no type declaration needed |
Comments | // single-line /* multi-line */ |
Adds notes to code |
If Statement | if (condition) { ... } | Conditional logic |
For Loop | for ($i = 0; $i < 10; $i++) { ... } | Iterates a fixed number of times |
While Loop | while (condition) { ... } | Repeats while condition is true |
Do-While Loop | do { ... } while (condition); | Executes at least once |
Foreach Loop | foreach ($array as $value) { ... } | Iterates over arrays |
Switch Statement | switch($var) { case 'a': ... break; default: ... } | Multi-branch selection |
Ternary Operator | $result = (condition) ? value1 : value2; | Shorthand for if/else |
Function Declaration | function myFunc($param) { ... } | Defines reusable code |
Indexed Array | $arr = array(1,2,3); | Numeric keys automatically assigned |
Associative Array | $assoc = array("key" => "value"); | Key-value pairs |
Constants | define("NAME", "value"); | Defines a constant value |
String Concatenation | $str = "Hello" . " World"; | Uses the dot operator |
Type Casting | (int)$var, (string)$var | Converts variable types |
Null Coalescing Operator | $var = $a ?? 'default'; | Returns left operand if set, else default |
Superglobals | $_GET, $_POST, $_SERVER, $_SESSION | Predefined global arrays |
File Inclusion | include 'file.php'; require 'file.php'; |
Inserts external PHP files |
Class Declaration | class MyClass { ... } | Defines an object-oriented class |
Interfaces | interface MyInterface { public function myMethod(); } | Contracts for classes |
Traits | trait MyTrait { ... } | Reusable sets of methods |
Anonymous Functions | $func = function($x) { return $x * 2; }; | Functions without a name (closures) |
Arrow Functions | $fn = fn($x) => $x + 1; | Shorter syntax for closures (PHP 7.4+) |
Error Handling | try { ... } catch (Exception $e) { ... } | Manages exceptions |
Sessions | session_start(); $_SESSION['user'] = 'Alice'; | Maintains user state |
Cookies | setcookie("name", "value", time()+3600); | Stores data on the client |
Regular Expressions | preg_match('/pattern/', $string, $matches); | Pattern matching in strings |
PDO (PHP Data Objects) | $pdo = new PDO($dsn, $user, $pass); | Database access abstraction layer |
JSON Functions | json_encode($data); json_decode($json); | Convert between JSON and PHP arrays/objects |
Date & Time Functions | date("Y-m-d"); time(); | Formats dates and gets the current timestamp |
Term | Explanation |
---|---|
PHP Opening Tag |
Every PHP script begins with the <?php tag and ends with ?> . These tags indicate to the server that the enclosed code should be executed as PHP. They are required at the beginning and end of your PHP code blocks.
|
Echo Statement |
The echo statement outputs one or more strings to the browser. For example, echo "Hello, World!"; will display the text. It’s one of the simplest ways to send output from your PHP code.
|
Variables |
Variables in PHP are declared with a dollar sign ($ ) followed by the variable name. PHP is loosely typed, so you do not have to declare a variable’s data type. For example, $name = "Alice"; stores a string, while $age = 30; stores an integer.
|
Comments |
Use // for single-line comments and /* ... */ for multi-line comments. Comments are ignored during execution and are used to explain your code.
|
Conditionals (If/Else) |
Conditional statements allow you to execute code based on a condition. For example, if ($x > 0) { ... } else { ... } executes different code blocks depending on whether $x is positive.
|
For Loop |
A for loop repeats a block of code a specific number of times. For example, for ($i = 0; $i < 10; $i++) { ... } runs the loop 10 times. It is commonly used when the number of iterations is known.
|
While Loop |
A while loop continues to execute as long as its condition remains true. For example, while ($x < 10) { ...; $x++; } will run until $x reaches 10.
|
Do-While Loop | The do-while loop executes the code block once and then repeats it as long as the condition is true. It ensures that the loop is executed at least once. |
Foreach Loop |
The foreach loop iterates over each element in an array. For example, foreach ($array as $value) { ... } processes each item in the array sequentially.
|
Switch Statement |
The switch statement compares a variable against multiple cases and executes the corresponding block. For example, switch($var) { case 'a': ... break; default: ... } is useful for handling multiple conditions.
|
Ternary Operator |
The ternary operator offers a shorthand way to write an if/else statement. For example, $result = ($x > 0) ? 'positive' : 'non-positive'; assigns a value based on the condition.
|
Function Declaration |
Functions are defined with the function keyword. They encapsulate code for reuse. For example, function add($a, $b) { return $a + $b; } creates a function that adds two numbers.
|
Arrays |
PHP supports both indexed and associative arrays. Indexed arrays use numeric keys (e.g., $arr = array(1,2,3); ), while associative arrays use named keys (e.g., $person = array("name" => "Alice", "age" => 30); ).
|
Constants |
Constants are defined using the define() function. For example, define("SITE_NAME", "My Website"); creates a constant that cannot be changed during script execution.
|
String Concatenation |
PHP concatenates strings using the dot operator. For example, $greeting = "Hello" . " " . "World!"; joins multiple strings into one.
|
Type Casting |
You can convert a variable’s type by casting it. For example, (int)$var casts a variable to an integer. This is useful when you need to ensure a variable is of a specific type.
|
Null Coalescing Operator |
The null coalescing operator (??) returns the left-hand operand if it exists and is not null; otherwise, it returns the right-hand operand. For example, $value = $data['key'] ?? 'default';
|
Superglobals |
Superglobals are built-in arrays accessible in any scope. Common examples include $_GET , $_POST , $_SERVER , and $_SESSION .
|
File Inclusion |
Use include or require to incorporate external PHP files. For example, require 'header.php'; embeds the contents of header.php.
|
Classes & Objects |
Define a class with class ClassName { ... } and instantiate it with $obj = new ClassName(); . Object-oriented programming helps structure code into reusable blueprints.
|
Interfaces |
Interfaces define methods that classes must implement. For example, interface Logger { public function log($msg); } forces implementing classes to define the log() method.
|
Traits |
Traits allow you to reuse methods across multiple classes. For example, trait MyTrait { function sayHi() { echo "Hi"; } } can be included in any class using the use keyword.
|
Anonymous Functions |
These are functions without a name, often used as callbacks. For example, $func = function($x) { return $x * 2; };
|
Arrow Functions |
Introduced in PHP 7.4, arrow functions provide a shorter syntax for anonymous functions. For example, $fn = fn($x) => $x + 1;
|
Error Handling |
Use try { ... } catch (Exception $e) { ... } to handle exceptions and errors gracefully, ensuring that your application can manage unexpected issues.
|
Sessions |
Sessions store user data between page requests. Start a session with session_start(); and use the $_SESSION superglobal to store and retrieve data.
|
Cookies |
Set cookies using setcookie("name", "value", time()+3600); to store small amounts of data on the client side.
|
Regular Expressions |
PHP supports regex functions like preg_match() and preg_replace() for pattern matching in strings.
|
PDO (PHP Data Objects) |
PDO provides a uniform method to access databases. For example, $pdo = new PDO($dsn, $user, $pass); establishes a database connection.
|
JSON Functions |
Convert PHP arrays and objects to JSON with json_encode() and back with json_decode() . These functions are essential for API development.
|
Date & Time Functions |
Functions like date() and time() are used to format dates and retrieve the current timestamp. For example, date("Y-m-d") returns today’s date.
|