PHP Cheatsheet (original) (raw)
**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 Cheatsheet
**What 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 `
`
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 `
`
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==a == a==b; |
Logical | &&, ` | |
Increment/Decrement | ++, -- | $count++; |
PHP `
a+a + 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 `
i<=3;i <= 3; 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"; } ?>`
Output
For 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 `
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"; } ?>`
Output
If 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.
Common Date and Time Formats
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 `
`
Output
2025-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.
Function | Description |
---|---|
strlen() | Returns length of a string |
strrev() | Reverses a string |
strtoupper() | Converts string to uppercase |
strtolower() | Converts string to lowercase |
strpos() | Finds position of a substring |
str_replace() | Replaces text within a string |
substr() | Extracts part of a string |
trim() | Trim spaces from both ends |
explode() | Splits string into an array |
implode() | Joins array elements into a string |
. (concatenation) | Joins two or more strings |
PHP `
gfg.gfg . 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)); ?>`
Output
GFG 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 `
"GFG", "age" => 30 ]; // Print associative array element echo $person["name"] . "\n"; ?>`
Output
apple 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 `
this−>brand=this->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(); ?>`
Output
The 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.