Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • PHP Tutorial
  • PHP Exercises
  • PHP Array
  • PHP String
  • PHP Calendar
  • PHP Filesystem
  • PHP Math
  • PHP Programs
  • PHP Array Programs
  • PHP String Programs
  • PHP Interview Questions
  • PHP GMP
  • PHP IntlChar
  • PHP Image Processing
  • PHP DsSet
  • PHP DsMap
  • PHP Formatter
  • Web Technology
Open In App
Next Article:
PHP Cheatsheet
Next article icon

PHP Cheatsheet

Last Updated : 24 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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-
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
<?php echo "Hello, World!"; ?> 

Output
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 ?> 

Output
PHP 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 $.

FeatureDescription
define()Defines a constant
const keywordAlternative way to define constants (PHP 5.3+)
Case-sensitivityConstants are case-sensitive by default
Global scopeConstants are accessible anywhere after declaration
No $ symbolConstants 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:

TypeDescriptionExample
StringText data enclosed in quotes$name = "Anjali";
IntegerWhole numbers$count = 10;
FloatDecimal numbers (also called double)$price = 15.75;
BooleanTrue or False$is_valid = true;
ArrayCollection of values stored in a single variable$colors = ["red", "blue"];
ObjectInstance of a class with properties and methods$car = new Car();
NULLRepresents a variable with no value assigned$empty = null;
ResourceSpecial 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 TypeDescriptionExamples
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 ?> 

Output
8 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 TypeDescriptionSyntax Example
forRepeats a block of code a specific number of timesfor (initialization; condition; increment) { }
whileExecutes code repeatedly while the condition is true (checks condition first)while (condition) { }
do-whileExecutes code once, then repeats while the condition is truedo { } while (condition);
foreachIterates over each element in an array or collectionforeach ($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"; } ?> 

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 TypeDescriptionSyntax Example
if-elseRuns code if a condition is true; otherwise runs the else blockif (condition) { } else { }
elseifAllows checking multiple conditions sequentiallyif (condition) { } elseif (condition) { } else { }
switchSelects one block of code to execute from many optionsswitch (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"; } ?> 

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

FormatDescriptionExample Output
Y4-digit year1996
m2-digit month (01 to 12)10
d2-digit day (01 to 31)13
HHour in 24-hour format (00-23)05
iMinutes (00-59)35
sSeconds (00-59)32
DDay of week (Mon, Tue, etc.)Sun
NISO-8601 numeric day of week (1 = Monday)7
PHP
<?php    echo date("Y-m-d H:i:s");  ?> 

Output
2025-05-24 09:28:55

DateTime Methods

MethodDescription
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
<?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)); ?> 

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.

FunctionDescription
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 PHPIterates 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";   ?> 

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.

SuperglobalDescription
$_GETHTTP GET variables
$_POSTHTTP POST variables
$_SERVERServer and execution environment information
$_SESSIONSession variables
$_COOKIEHTTP cookies
$_FILESUploaded 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.

TermDescription
classDefines a class
newCreates an object from a class
$thisRefers to the current object inside the class
publicProperty/method accessible from anywhere
privateAccessible only within the class
protectedAccessible within the class and its subclasses
__constructSpecial 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(); ?> 

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 NameDescription
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 NameDescription
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 NameDescription
E_ERRORFatal runtime errors.
E_WARNINGNon-fatal run-time warnings.
E_PARSECompile-time parse errors.
E_NOTICERun-time notices indicating possible errors.
E_CORE_ERRORErrors during PHP's initial startup.
E_CORE_WARNINGWarnings during PHP's initial startup.
E_COMPILE_ERRORFatal compile-time errors.
E_COMPILE_WARNINGCompile-time warnings.
E_USER_ERRORUser-generated error message (via trigger_error()).
E_USER_WARNINGUser-generated warning message.
E_USER_NOTICEUser-generated notice message.
E_STRICTSuggests code improvements for interoperability.
E_RECOVERABLE_ERRORCatchable fatal error.
E_DEPRECATEDWarns about deprecated code.
E_USER_DEPRECATEDUser-generated deprecated warning.
E_ALLReports 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:

  • PHP Tutorial
  • PHP Introduction
  • PHP Projects for Beginners
  • PHP Interview Questions

Next Article
PHP Cheatsheet

A

anjalisa6ys
Improve
Article Tags :
  • PHP

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 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
    Interesting Facts About PHP
    PHP is a widely-used open source and general purpose scripting language which is primarily made for web development. It can be merged into the HTML. Here are some interesting facts about PHP: The mascot of PHP is a big blue elephant.‘Personal Home Page’ is the original name of PHP.Today, PHP is reco
    2 min read
    New Features of PHP 7.4
    Introduction: PHP is a popular general-purpose scripting language. It is used for web development. It was created by Rasmus Lerdorf in 1994, the PHP reference implementation is now produced by the PHP Group. PHP 7.4 Update 2019: New features from time to time are very essential and important for any
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences