PHP stands for the Hypertext Preprocessor. It is a popular, open-source server-side scripting language designed for web development but also used as a general-purpose programming language. It is widely used to create dynamic web pages and can be embedded into HTML. PHP code is executed on the server, generating HTML that is then sent to the client.
This article provides an in-depth PHP Cheat Sheet, a must-have for every web developer.
PHP CheatsheetWhat is a PHP Cheatsheet?
A PHP Cheatsheet is a quick reference guide that shows the most important PHP commands, syntax, and examples all in one place. It helps programmers remember how to write PHP code easily without searching through long documents.
It’s like a summary of the basic and useful PHP things you need to know.
PHP Features
Here are some of the main features of PHP:
- Server-Side Scripting – Executes on the server to generate dynamic content.
- Simple Syntax – Easy to learn with C-like syntax.
- Cross-Platform – Runs on various operating systems like Linux, Windows, and macOS.
- Embedded in HTML – Easily integrated into HTML code.
- Supports Databases – Works with MySQL, PostgreSQL, SQLite, and others.
- Rich Built-in Functions – Provides thousands of built-in web and file handling functions.
- Object-Oriented – Supports classes, inheritance, interfaces, and traits.
- Large Community – Extensive support and numerous frameworks like Laravel, Symfony.
1. Basic Syntax
PHP scripts start with <?php
and end with ?>
.
PHP
<?php
echo "Hello, World!";
?>
2. Variables and Constants
Variables store data values. A variable starts with a $
sign followed by the name. PHP variables are dynamically typed, meaning you don’t need to declare their type.
Variable | Description |
---|
$name = "PHP"; | String value |
$age = 25; | Integer value |
$price = 9.99; | Float (decimal number) |
$is_active = true; | Boolean (true or false) |
PHP
<?php
$name = "PHP";
$age = 25;
$is_active = true;
echo $name . "\n"; // Outputs: PHP
echo $age; // Outputs: 25
?>
Constants
Constants in PHP are fixed values that do not change during script execution. They are defined using define()
or const
. They are globally accessible and do not begin with $
.
Feature | Description |
---|
define() | Defines a constant |
const keyword | Alternative way to define constants (PHP 5.3+) |
Case-sensitivity | Constants are case-sensitive by default |
Global scope | Constants are accessible anywhere after declaration |
No $ symbol | Constants are written without a dollar sign |
3. Magic Constants
Magic constants in PHP are built-in constants that change based on context, like file name, line number, or function name.
Magic Constant | Description |
---|
__LINE__ | Current line number of the file |
__FILE__ | Full path and filename of the file |
__DIR__ | Directory of the file |
__FUNCTION__ | Name of the current function |
__CLASS__ | Name of the current class |
__TRAIT__ | Name of the current trait |
__METHOD__ | Name of the current method |
__NAMESPACE__ | Name of the current namespace |
ClassName::class | It gives the complete name of the class, including its namespace, as a text value (string). |
4. Data Types
PHP supports several data types used to store different kinds of values:
Type | Description | Example |
---|
String | Text data enclosed in quotes | $name = "Anjali"; |
Integer | Whole numbers | $count = 10; |
Float | Decimal numbers (also called double) | $price = 15.75; |
Boolean | True or False | $is_valid = true; |
Array | Collection of values stored in a single variable | $colors = ["red", "blue"]; |
Object | Instance of a class with properties and methods | $car = new Car(); |
NULL | Represents a variable with no value assigned | $empty = null; |
Resource | Special variable that holds a reference to external resources like database connections or files | $handle = fopen("file.txt", "r"); |
5. Operators
PHP operators perform operations on variables and values.
Operator Type | Description | Examples |
---|
Arithmetic | + , - , * , / , % | $sum = 5 + 3; |
Assignment | = , += , -= , *= , /= | $a += 2; |
Comparison | == , === , != , !== , < , > | $a == $b; |
Logical | && , ` | |
Increment/Decrement | ++ , -- | $count++; |
PHP
<?php
$a = 5;
$b = 3;
echo $a + $b . "\n"; // 8
$a++;
echo $a; // 6
?>
6. Loops
PHP Loops are a useful feature in most programming languages. With loops you can evaluate a set of instructions/functions repeatedly until certain condition is reached.
Loop Type | Description | Syntax Example |
---|
for | Repeats a block of code a specific number of times | for (initialization; condition; increment) { } |
while | Executes code repeatedly while the condition is true (checks condition first) | while (condition) { } |
do-while | Executes code once, then repeats while the condition is true | do { } while (condition); |
foreach | Iterates over each element in an array or collection | foreach ($array as $value) { } |
PHP
<?php
// For Loop
echo "For Loop:\n";
for ($i = 1; $i <= 3; $i++) {
echo "Value of i: $i\n";
}
echo "\n";
// While Loop
echo "While Loop:\n";
$j = 1;
while ($j <= 3) {
echo "Value of j: $j\n";
$j++;
}
echo "\n";
// Do-While Loop
echo "Do-While Loop:\n";
$k = 4;
do {
echo "Value of k: $k\n";
$k++;
} while ($k < 4);
echo "\n";
// Foreach Loop
echo "Foreach Loop:\n";
$colors = ["Red", "Green", "Blue"];
foreach ($colors as $color) {
echo "Color: $color\n";
}
?>
OutputFor Loop:
Value of i: 1
Value of i: 2
Value of i: 3
While Loop:
Value of j: 1
Value of j: 2
Value of j: 3
Do-While Loop:
Value of k: 4
Foreach Loop:
Color: Red
Color: Green
Color: Blue
7. Conditional Statements
Conditional Statements is used in PHP to execute a block of codes conditionally. These are used to set conditions for your code block to run. If certain condition is satisfied certain code block is executed otherwise else code block is executed.
Statement Type | Description | Syntax Example |
---|
if-else | Runs code if a condition is true; otherwise runs the else block | if (condition) { } else { } |
elseif | Allows checking multiple conditions sequentially | if (condition) { } elseif (condition) { } else { } |
switch | Selects one block of code to execute from many options | switch (variable) { case value: ... break; default: ... } |
PHP
<?php
// If statement
$age = 20;
echo "If Statement:\n";
if ($age > 18) {
echo "You are an adult.\n";
}
echo "\n";
// If-Else statement
$score = 40;
echo "If-Else Statement:\n";
if ($score >= 50) {
echo "You passed.\n";
} else {
echo "You failed.\n";
}
echo "\n";
// If-Elseif-Else statement
$marks = 75;
echo "If-Elseif-Else Statement:\n";
if ($marks >= 90) {
echo "Grade: A\n";
} elseif ($marks >= 75) {
echo "Grade: B\n";
} elseif ($marks >= 50) {
echo "Grade: C\n";
} else {
echo "Grade: F\n";
}
echo "\n";
// Switch statement
$day = "Monday";
echo "Switch Statement:\n";
switch ($day) {
case "Monday":
echo "Start of the week.\n";
break;
case "Friday":
echo "Almost weekend.\n";
break;
case "Sunday":
echo "Rest day.\n";
break;
default:
echo "Just another day.\n";
}
?>
OutputIf Statement:
You are an adult.
If-Else Statement:
You failed.
If-Elseif-Else Statement:
Grade: B
Switch Statement:
Start of the week.
8. Date and Time
PHP Date and time provides powerful built-in functions and classes to work with dates and times. The main ways to handle dates are using the date()
function and the DateTime
class.
Format | Description | Example Output |
---|
Y | 4-digit year | 1996 |
m | 2-digit month (01 to 12) | 10 |
d | 2-digit day (01 to 31) | 13 |
H | Hour in 24-hour format (00-23) | 05 |
i | Minutes (00-59) | 35 |
s | Seconds (00-59) | 32 |
D | Day of week (Mon, Tue, etc.) | Sun |
N | ISO-8601 numeric day of week (1 = Monday) | 7 |
PHP
<?php
echo date("Y-m-d H:i:s");
?>
Output2025-05-24 09:28:55
DateTime Methods
Method | Description |
---|
format() | Formats the date/time as a string |
getTimestamp() | Returns the Unix timestamp |
modify() | Alters the date/time by adding or subtracting time |
setDate() | Sets the date (year, month, day) |
setTime() | Sets the time (hour, minute, second) |
9. Strings
Strings are sequences of characters used to store and manipulate text. PHP provides many built-in functions to work with strings, including concatenation, searching, replacing, slicing, and changing case.
PHP
<?php
$gfg = "GFG ";
$geeks = "stands-for-GeeksforGeeks";
// Concatenate strings
echo $gfg . $geeks . "\n";
// Find position of substring
echo strpos($geeks, "for") . "\n";
// Replace text
echo str_replace("FG", "fg", $gfg) . "\n";
// Extract substring
echo substr($geeks, 6, 3) . "\n";
// Convert to uppercase
echo strtoupper($geeks) . "\n";
// Split string into array and print
print_r(explode("-", $geeks));
?>
OutputGFG stands-for-GeeksforGeeks
7
Gfg
-fo
STANDS-FOR-GEEKSFORGEEKS
Array
(
[0] => stands
[1] => for
[2] => GeeksforGeeks
)
10. Arrays
Arrays in PHP are variables that store multiple values in one single variable. They can be indexed, associative and multidimensional array.
Function | Description |
---|
array() | Creates an array |
count() | Returns the number of elements in an array |
array_push() | Adds one or more elements to the end of an array |
array_pop() | Removes the last element from an array |
array_shift() | Removes the first element from an array |
array_unshift() | Adds one or more elements to the beginning of an array |
array_merge() | Merges one or more arrays |
in_array() | Checks if a value exists in an array |
sort() | Sorts an array |
foreach loop PHP | Iterates over each element in an array |
PHP
<?php
// Indexed array
$fruits = ["apple", "banana", "cherry"];
// Add element to the end
array_push($fruits, "orange");
// Remove last element
array_pop($fruits);
// Iterate over array and print each element
foreach ($fruits as $fruit) {
echo $fruit . "\n";
}
// Associative array
$person = [
"name" => "GFG",
"age" => 30
];
// Print associative array element
echo $person["name"] . "\n";
?>
Outputapple
banana
cherry
GFG
11. Superglobals
PHP superglobals are built-in variables accessible everywhere, holding data like form input, sessions, cookies, server info, and files.
Superglobal | Description |
---|
$_GET | HTTP GET variables |
$_POST | HTTP POST variables |
$_SERVER | Server and execution environment information |
$_SESSION | Session variables |
$_COOKIE | HTTP cookies |
$_FILES | Uploaded files |
12. Classes and Objects
In PHP, a Class is a blueprint for creating objects. It groups variables (properties) and functions (methods) into a single unit.
An object is an instance of a class. It allows you to access the class’s properties and methods.
Term | Description |
---|
class | Defines a class |
new | Creates an object from a class |
$this | Refers to the current object inside the class |
public | Property/method accessible from anywhere |
private | Accessible only within the class |
protected | Accessible within the class and its subclasses |
__construct | Special method called automatically when object is created |
PHP
<?php
// Define a class
class Car {
// Property
public $brand;
// Constructor
public function __construct($brand) {
$this->brand = $brand;
}
// Method
public function displayBrand() {
echo "The car brand is: " . $this->brand;
}
}
// Create an object of the class
$myCar = new Car("Toyota");
// Call the method
$myCar->displayBrand();
?>
OutputThe car brand is: Toyota
Math
PHP offers numerous mathematical functions that allow you to perform operations like rounding, trigonometry, logarithms, and more. Here are the most commonly used functions:
Function Name | Description |
---|
abs(x) | Returns the absolute (positive) value of x |
ceil(x) | Rounds x up to the nearest integer |
floor(x) | Rounds x down to the nearest integer |
round(x) | Rounds x to the nearest integer |
max(x, y, ...) | Returns the highest value among the arguments |
min(x, y, ...) | Returns the lowest value among the arguments |
sqrt(x) | Returns the square root of x |
pow(x, y) | Returns x raised to the power of y |
rand(min, max) | Returns a random integer between min and max |
mt_rand(min, max) | Returns a better random integer (faster and more random) |
pi() | Returns the value of π (3.14159...) |
deg2rad(x) | Converts degrees to radians |
rad2deg(x) | Converts radians to degrees |
bindec(string) | Converts binary to decimal |
decbin(number) | Converts decimal to binary |
hexdec(string) | Converts hexadecimal to decimal |
dechex(number) | Converts decimal to hexadecimal |
log(x, base) | Returns the logarithm of x in the given base (default is e) |
exp(x) | Returns Euler's number raised to the power of x |
fmod(x, y) | Returns the remainder (modulo) of x ÷ y |
14. PHP Errors
PHP Errors occur when something goes wrong while a script is running. Errors help developers identify and fix problems in the code.
There are different types of errors depending on the nature of the issue. Majorly there are the four types of the errors:
- Syntax Error or Parse Error
- Fatal Error
- Warning Error
- Notice Error
PHP Error Functions
PHP Error Functions manage how errors are reported, displayed, logged, or handled using built-in or custom error-handling mechanisms.
Function Name | Description |
---|
error_reporting() | Sets which PHP errors are reported. |
ini_set() | Sets configuration options at runtime (e.g., display_errors). |
trigger_error() | Generates a user-level error/warning/notice. |
set_error_handler() | Defines a custom function to handle errors. |
restore_error_handler() | Restores the previous error handler function. |
set_exception_handler() | Sets a function to handle uncaught exceptions. |
restore_exception_handler() | Restores the previous exception handler function. |
PHP Error Constants
PHP error constants represent different error types like warnings, notices, and fatal errors, allowing developers to control error reporting behavior.
Constant Name | Description |
---|
E_ERROR | Fatal runtime errors. |
E_WARNING | Non-fatal run-time warnings. |
E_PARSE | Compile-time parse errors. |
E_NOTICE | Run-time notices indicating possible errors. |
E_CORE_ERROR | Errors during PHP's initial startup. |
E_CORE_WARNING | Warnings during PHP's initial startup. |
E_COMPILE_ERROR | Fatal compile-time errors. |
E_COMPILE_WARNING | Compile-time warnings. |
E_USER_ERROR | User-generated error message (via trigger_error() ). |
E_USER_WARNING | User-generated warning message. |
E_USER_NOTICE | User-generated notice message. |
E_STRICT | Suggests code improvements for interoperability. |
E_RECOVERABLE_ERROR | Catchable fatal error. |
E_DEPRECATED | Warns about deprecated code. |
E_USER_DEPRECATED | User-generated deprecated warning. |
E_ALL | Reports all PHP errors (includes all above). |
Benefits of Using PHP Cheatsheet
Below are some key benefits of a PHP Cheatsheet:
- Faster Development: A PHP Cheat Sheet helps programmers quickly find the right code or syntax, so they can write programs faster without wasting time searching.
- Complete Reference: It includes common PHP commands, functions, and examples, which is useful for both beginners learning PHP and experienced developers needing a quick reminder.
- Build Dynamic Websites: PHP Cheat Sheet helps create interactive and dynamic web pages by providing easy access to PHP functions for working with forms, databases, and user input.
- Works Well with Other Web Technologies: PHP often works together with HTML, CSS. The cheat sheet helps understand how PHP fits in the whole web development process.
- Better Code Quality: Using the right PHP functions and syntax from the cheat sheet helps write cleaner, more reliable code.
- Handles Web Tasks Easily: The cheat sheet covers important tasks like working with files, sessions, and error handling, making websites more efficient and user-friendly.
Recommended Links:
Similar Reads
PHP | Spreadsheet
Introduction: PHPSpreadsheet is a library written in PHP which helps to read from and write to different types of spreadsheet file formats with the help of a given set of classes. The various format which support spreadsheet are Excel(.xlsx), Open Document Format(.ods),SpreadsheetML(.xml), CSV and m
2 min read
PHP list() Function
The list() function is an inbuilt function in PHP which is used to assign array values to multiple variables at a time. This function will only work on numerical arrays. When the array is assigned to multiple values, then the first element in the array is assigned to the first variable, second to th
2 min read
PHP | Functions
A function in PHP is a self-contained block of code that performs a specific task. It can accept inputs (parameters), execute a set of statements, and optionally return a value. PHP functions allow code reusability by encapsulating a block of code to perform specific tasks.Functions can accept param
8 min read
PHP | each() Function
The each() function is an inbuilt function in PHP which basically returns an array with four elements, two elements (1 and Value) for the element value, and two elements (0 and Key) for the element key and moves the cursor forward. Syntax: each(array) Parameters: Array: It specifies the array which
2 min read
PHP cosh( ) Function
The cosh() function is a builtin function in PHP and is used to find the hyperbolic sine of an angle. The hyperbolic cosine of any argument arg is defined as, (exp(arg) + exp(-arg))/2 Where, exp() is the exponential function and returns e raised to the power of argument passed to it. For example exp
2 min read
PHP Math Functions
PHP is a scripting language that comes with many built-in math functions and constants. These tools help you do basic math, solve more complex problems, and work with different math concepts. This guide gives an overview of PHP's math functions and constants, along with examples, practical uses, and
5 min read
PHP Arrays
Arrays are one of the most important data structures in PHP. They allow you to store multiple values in a single variable. PHP arrays can hold values of different types, such as strings, numbers, or even other arrays. Understanding how to use arrays in PHP is important for working with data efficien
5 min read
PHP acosh( ) Function
In mathematics, the inverse hyperbolic functions are the inverse functions of the hyperbolic functions. For a given value of a hyperbolic function, the corresponding inverse hyperbolic function provides the corresponding hyperbolic angle. PHP provides us with builtin functions for inverse hyperbolic
1 min read
PHP hypot() function
The hypot() function is a built-in mathematical function in PHP and returns the square root of sum of square of arguments passed. It finds the hypotenuse, hypotenuse is the longest side of a right angled triangle. It is calculated by the formula : h = \sqrt{x^2+y^2} where x and y are the other two s
1 min read
PHP asinh( ) Function
In mathematics, the inverse hyperbolic functions are the inverse functions of the hyperbolic functions. For a given value of a hyperbolic function, the corresponding inverse hyperbolic function provides the corresponding hyperbolic angle. PHP provides us with builtin functions for inverse hyperbolic
1 min read