![]() |
VOOZH | about |
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.
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.
Here are some of the main features of PHP:
PHP scripts start with <?php and end with ?>.
Hello, World!
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 25
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 |
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). |
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"); |
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++; |
8 6
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) { } |
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
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: ... } |
If Statement: You are an adult. If-Else Statement: You failed. If-Elseif-Else Statement: Grade: B Switch Statement: Start of the week.
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 |
2025-05-24 09:28:55
| 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) |
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 |
|---|---|
Returns length of a string | |
Reverses a string | |
Converts string to uppercase | |
Converts string to lowercase | |
Finds position of a substring | |
Replaces text within a string | |
Extracts part of a string | |
Trim spaces from both ends | |
Splits string into an array | |
Joins array elements into a string | |
| Joins two or more strings |
GFG stands-for-GeeksforGeeks 7 Gfg -fo STANDS-FOR-GEEKSFORGEEKS Array ( [0] => stands [1] => for [2] => GeeksforGeeks )
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 |
apple banana cherry GFG
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 |
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 |
The car brand is: Toyota
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 |
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:
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 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). |
Below are some key benefits of a PHP Cheatsheet: