Table of Contents
PHP Cheatsheet: Your Essential Guide to Modern PHP Development
PHP, a widely-used open-source scripting language, has been the backbone of countless websites and web applications for decades. From simple personal blogs to complex enterprise systems, PHP’s versatility and robust ecosystem make it a go-to choice for web developers worldwide. This cheatsheet is designed to be your quick reference guide, covering essential syntax, core concepts, and common functions in modern PHP development.
Whether you’re a seasoned developer needing a quick reminder or a newcomer looking for a structured overview, this guide will help you navigate the fundamentals and advanced features of PHP efficiently.
1. Fundamentals: Syntax and Basic Constructs
PHP code is typically embedded within HTML. The server processes the PHP code and sends the resulting HTML to the client’s browser.
PHP Tags and Comments
PHP code blocks are enclosed within special tags.
- Standard Tags:
<?php ... ?>(Recommended) - Short Echo Tag:
<?= ... ?>(Shorthand for<?php echo ... ?>, useful for displaying variables quickly)
<?php
// This is a single-line comment
/
This is a multi-line comment block.
It can span multiple lines.
/
echo "Hello, World!"; // This is also a single-line comment
?>
<p>The current year is: <?= date('Y'); ?></p>
Statements and Semicolons
Every statement in PHP must end with a semicolon (;), except for the closing tag of a PHP block.
<?php
$name = "Alice";
echo "My name is " . $name; // Semicolon required
?>
Variables and Constants
Variables
- Variables start with a dollar sign (
$). - They are case-sensitive (
$nameis different from$Name). - No explicit type declaration is needed; PHP is dynamically typed.
<?php
$age = 30; // Integer
$name = "Bob"; // String
$is_active = true; // Boolean
echo $name . " is " . $age . " years old.";
?>
Constants
- Defined using
define()function or theconstkeyword. - Once defined, their value cannot be changed.
- By convention, constant names are uppercase.
<?php
define("SITE_NAME", "My Awesome Site");
const MAX_USERS = 1000;
echo SITE_NAME;
echo MAX_USERS;
?>
Data Types
PHP supports several primitive and compound data types.
Scalar Types
- Integer: Whole numbers (e.g.,
10,-5,0x1A). - Float (Double): Numbers with decimal points (e.g.,
3.14,2.0). - String: Sequence of characters enclosed in single (
') or double (") quotes. Double quotes allow variable interpolation. - Boolean:
trueorfalse(case-insensitive).
<?php
$int_var = 123;
$float_var = 12.34;
$string_var = "Hello, PHP!";
$bool_var = true;
echo gettype($int_var); // Output: integer
echo gettype($string_var); // Output: string
echo "The value of bool_var is: " . ($bool_var ? "true" : "false");
?>
Compound Types
- Array: Ordered map. Can hold values of different types.
- Object: Instances of classes.
<?php
$my_array = [1, "two", true]; // Indexed array
$user = ["name" => "John", "age" => 30]; // Associative array
class Person {
public $name;
function __construct($name) {
$this->name = $name;
}
}
$person_obj = new Person("Jane");
?>
Special Types
- NULL: A variable with no value, or explicitly assigned
NULL. - Resource: Special variables holding references to external resources (e.g., database connections, file handles).
<?php
$null_var = null;
echo is_null($null_var); // Output: 1 (true)
?>
2. Operators
Operators are used to perform operations on variables and values.
Web3 Fellowship Programs: Top Opportunities for Developers
Master Writing Scholarship Essays: Winning Templates and Expert Tips
10 Best Webinar Platforms in February 2026 [Free+Paid]
Arithmetic Operators
Used for mathematical calculations.
| Operator | Description | Example | Result |
|---|---|---|---|
+ |
Addition | $x = 10 + 5; |
15 |
- |
Subtraction | $x = 10 - 5; |
5 |
|
Multiplication | $x = 10 5; |
50 |
/ |
Division | $x = 10 / 5; |
2 |
% |
Modulus | $x = 10 % 3; |
1 |
|
Exponentiation | $x = 2 3; |
8 |
Assignment Operators
Used to assign values to variables.
| Operator | Example | Equivalent To |
|---|---|---|
= |
$x = 10; |
$x = 10; |
+= |
$x += 5; |
$x = $x + 5; |
-= |
$x -= 5; |
$x = $x - 5; |
= |
$x = 5; |
$x = $x 5; |
/= |
$x /= 5; |
$x = $x / 5; |
%= |
$x %= 3; |
$x = $x % 3; |
. |
$str .= "hi"; |
$str = $str . "hi"; |
Comparison Operators
Used to compare two values. They return a boolean true or false.
| Operator | Description | Example | Result |
|---|---|---|---|
== |
Equal (value) | 10 == "10" |
true |
=== |
Identical (value & type) | 10 === "10" |
false |
!= |
Not equal (value) | 10 != 5 |
true |
!== |
Not identical | 10 !== "10" |
true |
< |
Less than | 5 < 10 |
true |
> |
Greater than | 10 > 5 |
true |
<= |
Less than or equal to | 10 <= 10 |
true |
>= |
Greater than or equal to | 10 >= 5 |
true |
<=> |
Spaceship (PHP 7+) | 1 <=> 2 (-1), 2 <=> 1 (1), 1 <=> 1 (0) |
Logical Operators
Used to combine conditional statements.
| Operator | Description | Example | Result |
|---|---|---|---|
&& |
And | $a && $b (both true) |
true |
| ` | ` | Or | |
! |
Not | !$a (inverts boolean value) |
true |
Increment/Decrement Operators
Used to increase or decrease a variable’s value by one.
| Operator | Description | Example |
|---|---|---|
++$x |
Pre-increment | Increments $x by one, then returns $x. |
$x++ |
Post-increment | Returns $x, then increments $x by one. |
--$x |
Pre-decrement | Decrements $x by one, then returns $x. |
$x-- |
Post-decrement | Returns $x, then decrements $x by one. |
String Operator
.: Concatenation (joins two strings).
<?php
$greeting = "Hello" . " " . "World!"; // "Hello World!"
?>
Ternary Operator
A shorthand for if...else statements.
<?php
$age = 20;
$status = ($age >= 18) ? "Adult" : "Minor"; // Output: Adult
?>
Null Coalescing Operator (??, PHP 7+)
Returns its first operand if it exists and is not NULL; otherwise, it returns its second operand.
<?php
$username = $_GET['user'] ?? 'Guest'; // If $_GET['user'] is not set or is null, $username becomes 'Guest'
?>
3. Control Flow
Control flow statements allow you to execute code conditionally or repeatedly.
Conditional Statements
if, else if, else
Executes different blocks of code based on conditions.
<?php
$score = 85;
if ($score >= 90) {
echo "Grade: A";
} elseif ($score >= 80) {
echo "Grade: B";
} else {
echo "Grade: C or lower";
}
?>
switch
Executes different blocks of code based on the value of a single variable.
<?php
$day = "Monday";
switch ($day) {
case "Monday":
echo "Start of the week.";
break;
case "Friday":
echo "End of the week!";
break;
default:
echo "Mid-week day.";
}
?>
Loops
for Loop
Repeats a block of code a specified number of times.
<?php
for ($i = 0; $i < 5; $i++) {
echo "Iteration " . $i . "<br>";
}
?>
foreach Loop
Iterates over elements in an array or object.
<?php
$colors = ["red", "green", "blue"];
foreach ($colors as $color) {
echo $color . "<br>";
}
$user = ["name" => "Alice", "age" => 25];
foreach ($user as $key => $value) {
echo $key . ": " . $value . "<br>";
}
?>
while Loop
Repeats a block of code as long as a specified condition is true.
<?php
$count = 0;
while ($count < 3) {
echo "Count: " . $count . "<br>";
$count++;
}
?>
do-while Loop
Similar to while, but the block is executed at least once before the condition is checked.
<?php
$i = 0;
do {
echo "The number is: " . $i . "<br>";
$i++;
} while ($i < 5);
?>
break and continue
break: Terminates the current loop orswitchstatement.continue: Skips the rest of the current loop iteration and proceeds to the next iteration.
<?php
for ($i = 0; $i < 10; $i++) {
if ($i == 3) {
continue; // Skip 3
}
if ($i == 7) {
break; // Stop at 7
}
echo $i . " "; // Output: 0 1 2 4 5 6
}
?>
4. Functions
Functions are blocks of code designed to perform a specific task.
Defining and Calling Functions
<?php
function greet($name) {
return "Hello, " . $name . "!";
}
echo greet("World"); // Output: Hello, World!
?>
Parameters and Return Types
- Default Parameters: Assign default values to parameters.
- Type Declarations (PHP 7+): Specify expected data types for parameters and return values.
<?php
function add(int $a, int $b = 0): int {
return $a + $b;
}
echo add(5); // Output: 5 (b defaults to 0)
echo add(5, 3); // Output: 8
?>
Anonymous Functions (Closures)
Functions without a name, often used as callbacks.
<?php
$numbers = [1, 2, 3, 4];
$squared_numbers = array_map(function($n) {
return $n $n;
}, $numbers);
print_r($squared_numbers); // Output: Array ( [0] => 1 [1] => 4 [2] => 9 [3] => 16 )
?>
Arrow Functions (fn, PHP 7.4+)
A more concise syntax for anonymous functions with a single expression.
<?php
$factor = 2;
$multiply = fn($num) => $num * $factor;
echo $multiply(5); // Output: 10
?>
5. Arrays
Arrays are ordered maps that can store multiple values in a single variable.
Indexed Arrays
Elements are accessed using numeric indices (starting from 0).
<?php
$fruits = ["apple", "banana", "cherry"];
echo $fruits[0]; // Output: apple
$fruits[] = "date"; // Add to the end
print_r($fruits); // Output: Array ( [0] => apple [1] => banana [2] => cherry [3] => date )
?>
Associative Arrays
Elements are accessed using named keys.
<?php
$person = [
"name" => "Jane Doe",
"age" => 30,
"city" => "New York"
];
echo $person["name"]; // Output: Jane Doe
$person["occupation"] = "Developer"; // Add new key-value pair
print_r($person);
?>
Multidimensional Arrays
Arrays containing other arrays.
<?php
$matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
echo $matrix[1][2]; // Output: 6
?>
Common Array Functions
count($array): Returns the number of elements.array_push($array, $value1, ...): Pushes one or more elements onto the end of an array.array_pop($array): Pops the last element off the end of an array.array_merge($array1, $array2, ...): Merges one or more arrays.in_array($needle, $haystack): Checks if a value exists in an array.array_keys($array): Returns all the keys of an array.array_values($array): Returns all the values of an array.sort($array): Sorts an indexed array in ascending order.rsort($array): Sorts an indexed array in descending order.asort($array): Sorts an associative array by value in ascending order.ksort($array): Sorts an associative array by key in ascending order.array_map($callback, $array): Applies a callback function to the elements of the given arrays.array_filter($array, $callback): Filters elements of an array using a callback function.array_reduce($ (Note: MAX_TOKENS)array, $callback, $initial): Iteratively reduce
Have any thoughts?
Share your reaction or leave a quick response — we’d love to hear what you think!