HTML Cheat Sheet

Editor 🖍

Syntax-highlighted code editor


Basics 🚼

Basic PHP syntax

Hello World!

$i = "World!";
echo "Hello ".$i; 


// One liner

# another one liner

/* This is
a multiline

Defining Functions

function sayHello() {
    echo "Hello!";
sayHello(); // Outputs: Hello!


$i = 1;
$pi = 3.14;
$stringName = "value";
$names = array("John","Jane","Jack");


Dumps information about a variable.

$a = array(1, 2, array("a", "b", "c"));


class foo {
   function do_foo() {
     echo "Doing foo."; 
$bar = new foo;

Escaping characters

echo "\n"; //New line
Line feed \n
Carriage return \r
Horizontal tab space \t
Vertical tab \v
Escape characters \e
Form (page or section separator)  \f
Backslash \\
Dollar sign \$
Single quote \'
Double quote \"

Loops ➰

For and while loops in PHP

For Loop

// For loop count to 10
for( $i = 0; $i < 10; $i += 1) { 
    echo $i . "\n"; 

Foreach Loop

// Declare an array 
$arr = array("tesla", "bmw", "audi");  
// Loop through the array elements 
foreach ($arr as $element) { 
    echo "$element "; 

While Loop

// Declare a number 
$i = 10; 
// Counting down to 0
while ($i >= 0) { 
  echo $i . "\n"; 

Do-While Loop

$i = 10; 
// Counting back to 0
do { 
    echo $i . "\n"; 
} while ($i >= 0); 


We show ads to support this free website.

Operators 🔣

The compiler performs specific mathematical or logical manipulations.

Hover your mouse for explanation.

$x + $y Addition
$x - $y Subtraction
$x * $y Multiplication
$x / $y Division
$x % $y Modulus
$x ** $y Exponentiation


x = y x = y
x = x + y x += y
x = x - y x -= y
x = x * y x *= y
x = x / y x /= y
x = x % y x %= y


$x == $y Equal
$x === $y Identical
$x != $y Not equal
$x <> $y Not equal
$x !== $y Not identical
$x > $y Greater than
$x < $y Less than
$x >= $y Greater than or equal to
$x <= $y Less than or equal to
=++$x Pre-increment
$x++ Post-increment
--$x Pre-decrement
$x-- Post-decrement


!$x Not
$x and $y $x && $y And
$x or $y $x || $y Or
$x xor $y Xor


$s1 . $s2 Concatenation
$s1 .= $s2 Concatenation assignment


$x + $y Union
$x == $y Equality
$x === $y Identity
$x != $y Inequality
$x <> $y Inequality
$x !== $y Non-identity

Conditions ⤭

Conditional Assignment Operators

If statement

if (condition) { 
// execute this if condition is true

If - Else

if (condition) { 
  // do this if condition is true
} else { 
  // do this if condition is false

If - Elseif - Else

if (condition) { 
  // code if condition is true
} elseif (condition2) { 
  // condition is false and condition2 is true
} else { 
  // if none of the conditions are met 

Switch Statement

switch (n) { 
case a: 
  //code to execute if n=a; 
case b: 
  //code to execute if n=b; 
case c: 
  //code to execute if n=c; 
  // more cases as needed 
  // if n is neither of the above; 


Variable = (Condition) ? (Statement1) : (Statement2);

$result = condition ? value1 : value2;

Is the same as:

if (condition) {
	$result = value1;
} else {
	$result = value2;

Functions ♞

Functions are reusable blocks of code that perform specific tasks


function greet($name) {
    echo "Hello " . $name;
// Outputs: Hello John

Default Parameters

function greet($name = "Visitor") {
    echo "Hello, " . $name;
greet(); // Outputs: Hello, Visitor

Return Values

function add($a, $b) {
    return $a + $b;
$result = add(3, 5); 
// $result is 8

Variable Scope

$number = 10;
function multiplyByTwo() {
    global $number;
    $number *= 2;
echo $number; // Outputs: 20

Anonymous Functions

$greet = function($name) {
    echo "Hello, " . $name;
$greet("Alice"); // Outputs: Hello, Alice

Built-in Functions

Built-in functions for various tasks, such as string manipulation, array handling, file operations etc..

  • String: strlen(), str_replace(), substr()
  • Array: array_merge(), array_pop(), array_keys()
  • Math: abs(), ceil(), floor()
  • Date: date(), strtotime(), mktime()
  • File: fopen(), fwrite(), fread()

Arrays ⧚

A PHP array is a data structure that can store multiple values of different types under a single variable name, indexed either numerically or associatively.

Indexed arrays

$colors = array("Red", "Green", "Blue");
echo $colors[0]; // Outputs: Red

Associative arrays

$age = array("Peter" => 35, "Ben" => 37, "Joe" => 43);
echo $age['Peter']; // Outputs: 35

Multidimensional arrays

$students = array(
  "John" => array("Math" => 123, "Science" => 456),
  "Jane" => array("Math" => 789, "Science" => 987)
echo $students['John']['Math']; // Outputs: 123

Array Functions

Hover your mouse for explanation

array_change_key_case, array_chunk, array_column, array_combine, array_count_values, array_diff, array_diff_assoc, array_diff_key, array_diff_uassoc, array_diff_ukey, array_fill, array_fill_keys, array_filter, array_flip, array_intersect, array_intersect_assoc, array_intersect_key, array_intersect_uassoc, array_intersect_ukey, array_key_exists, array_keys, array_map, array_merge, array_merge_recursive, array_multisort, array_pad, array_pop, array_product, array_push, array_rand, array_reduce, array_replace, array_replace_recursive, array_reverse, array_search, array_shift, array_slice, array_splice, array_sum, array_udiff, array_udiff_assoc, array_udiff_uassoc, array_uintersect, array_uintersect_assoc, array_uintersect_uassoc, array_unique, array_unshift, array_values, array_walk, array_walk_recursive, arsort, asort, compact, count, current, each, end, extract, in_array, key, krsort, ksort, list, natcasesort, natsort, next, prev, range, reset, rsort, shuffle, sort, uasort, uksort, usort

Predefined Variables 🌎

PHP offers a wide range of predefined variables to all scripts, encompassing everything from external inputs to built-in environment variables, last error messages, and more. This information is accessible through these variables.


They can be accessed from any scope. Variables in the outermost scope are automatically global and can be used inside functions. To use a global variable within a function, you must either declare it with the global keyword or use the $GLOBALS syntax.

$a = 5; 
$b = 10; 
function addition() { 
  $GLOBALS['sum'] = $GLOBALS['a'] + $GLOBALS['b']; 
echo $sum; 

Super Global Variables

Hover your mouse for explanation


PHP Forms ✍

An associative array of variables passed to the current script via the URL parameters (query string).


It's used for retrieving data from URL parameters (query string).

// URL:
$x = $_GET['x'];  // $x will be 1


Used for retrieving data from form submissions via HTTP POST method.

$username = $_POST['username']; 
// Variable will contain the value entered in the form

Sent through form.php

<form method="post" action="form.php">
  <input type="text" name="username">
   <input type="submit">


A general-purpose array that combines $_GET, $_POST, and $_COOKIE.

Example for the same HTML as above:

    $username = $_REQUEST['username'];
    echo "Hello, " . htmlspecialchars($username);

Security 👮

Always sanitize and validate user input on the server-side

  • htmlspecialchars(): This function converts special characters to HTML entities. 
  • trim(): This function removes whitespace (or other characters specified) from the beginning and end of a string.
  • stripslashes(): This function removes backslashes (\) from a string.
// Assuming form submission
    // Sanitize and trim input
    $input = htmlspecialchars($_POST['input_field'], ENT_QUOTES, 'UTF-8');
    $input = trim($input);
    // Handle magic_quotes_gpc scenario if needed
    if (get_magic_quotes_gpc()) {
        $input = stripslashes($input);
    // $input is now safe to use for further processing or storage

Predefined Functions

These PHP variable handling functions are part of the PHP core and there's no installation required to use them.


Returns the boolean value of a variable

[1, 2]true
new stdClasstrue


To check whether a variable is empty

$x = 0; 
if (isset($x)) { 
echo "x is set"; 
// True because $x is set 


Unsets variable

$x = "Hello world!"; 
echo "before unset: " . $x; 
echo "after unset: " . $a;
// Throws warning for undefined variable


Provides a detailed dump of a variable's reference count and type information.

$a = "Hello, World!";
$b = $a;
$c = &$a;

string(13) "Hello, World!" interned


Check whether a variable is empty or not

input empty(input)
"" true
0 true
php false


Converts a given variable to a floating-point number

input floatval(input)
12.3 12.3
"12.3abc" 12.3
true 1
"abc" 0


Returns the resource type of a given resource variable

// prints: stream 
$fp = fopen("file", "w"); 
echo get_resource_type($fp) . "\n"; 
// prints: curl 
$c = curl_init (); 
echo get_resource_type($c) . "\n";


Used to obtain the type of a given resource

// Open a file handle
$file = fopen("example.txt", "r");
// Get the type of the resource
echo get_resource_type($file); // Outputs: "stream"
// Close the file handle


Used to determine the type of a given variable

"HTML Cheat Sheet"string
array(1, 2, 3)array
fopen("file.txt", "r")resource


Integer value of a variable

"101010"intval("101010", 2) => 42


To check whether a given variable is an array

Database 🖧

MySQLi (MySQL Improved) is an extension for PHP that provides an interface for interacting with MySQL databases.

Connecting to DB

$mysqli = mysqli_connect("localhost", "username", "password", "database");
if (!$mysqli) {
    die("Connection failed: " . mysqli_connect_error());
$mysqli = new mysqli("localhost", "username", "password", "database");
if ($mysqli->connect_error) {
    die("Connection failed: " . $mysqli->connect_error);


$result = mysqli_query($mysqli, "SELECT * FROM table_name");
if ($result) {
    while ($row = mysqli_fetch_assoc($result)) {
        echo $row["column_name"];
$result = $mysqli->query("SELECT * FROM table_name");
if ($result) {
    while ($row = $result->fetch_assoc()) {
        echo $row["column_name"];

Prepared Statements

$stmt = mysqli_prepare($mysqli, "SELECT * FROM table_name WHERE column_name = ?");
mysqli_stmt_bind_param($stmt, "s", $value);
$result = mysqli_stmt_get_result($stmt);
while ($row = mysqli_fetch_assoc($result)) {
    echo $row["column_name"];
$stmt = $mysqli->prepare("SELECT * FROM table_name WHERE column_name = ?");
$stmt->bind_param("s", $value);
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    echo $row["column_name"];

Inserting Data

$sql = "INSERT INTO table_name (column1, column2) VALUES ('value1', 'value2')";
if (mysqli_query($mysqli, $sql)) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . mysqli_error($mysqli);
$sql = "INSERT INTO table_name (column1, column2) VALUES ('value1', 'value2')";
if ($mysqli->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $mysqli->error;

Updating Data

$sql = "UPDATE table_name SET column1 = 'value' WHERE condition";
if (mysqli_query($mysqli, $sql)) {
    echo "Record updated successfully";
} else {
    echo "Error: " . $sql . "<br>" . mysqli_error($mysqli);
$sql = "UPDATE table_name SET column1 = 'value' WHERE condition";
if ($mysqli->query($sql) === TRUE) {
    echo "Record updated successfully";
} else {
    echo "Error: " . $sql . "<br>" . $mysqli->error;

Deleting Data

$sql = "DELETE FROM table_name WHERE condition";
if (mysqli_query($mysqli, $sql)) {
    echo "Record deleted successfully";
} else {
    echo "Error: " . $sql . "<br>" . mysqli_error($mysqli);
$sql = "DELETE FROM table_name WHERE condition";
if ($mysqli->query($sql) === TRUE) {
    echo "Record deleted successfully";
} else {
    echo "Error: " . $sql . "<br>" . $mysqli->error;

Closing the Connection


Common Functions Overview

  • Connecting: mysqli_connect, mysqli_connect_error, mysqli_close
  • Queries: mysqli_query, mysqli_fetch_assoc, mysqli_num_rows
  • Prepared Statemen: mysqli_prepare, mysqli_stmt_bind_param, mysqli_stmt_execute, mysqli_stmt_get_result, mysqli_stmt_close
  • Error Handling: mysqli_error, mysqli_stmt_error


We show ads to support this free website.

Regular Exprressions 🤯

RegEx syntax and functions


$exp = "/cheatsheet/i";

$email = "";
if (preg_match('/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/', $email)) {
    echo "Valid email address";
} else {
    echo "Invalid email";

RegEx Functions

preg_match() - Returns 1 if the pattern was found in the string and 0 if not

preg_match_all() - Returns the number of times the pattern was found in the string, which may also be 0

preg_replace() - Returns a new string where matched patterns have been replaced with another string


i - Performs a case-insensitive search

m - Performs a multiline search (patterns that search for the beginning or end of a string will match the beginning or end of each line)

u - Enables correct matching of UTF-8 encoded patterns


[abc] – Find one character from the options between the brackets

[^abc] – Find any character NOT between the brackets

[0-9] – Find one character from the range 0 to 9


| - Find a match for any one of the patterns separated by | as in: cat|dog|fish

- Find just one instance of any character

^ - Finds a match as the beginning of a string as in: ^Hello

$ - Finds a match at the end of the string as in: World$

\d - Find a digit

\s -Find a whitespace character

\b - Find a match at the beginning of a word like this: \bWORD, or at the end of a word like this: WORD\b

\uxxxx - Find the Unicode character specified by the hexadecimal number xxxx


n+ - Matches any string that contains at least one n

n* - Matches any string that contains zero or more occurrences of n

n? - Matches any string that contains zero or one occurrences of n

n{x} - Matches any string that contains a sequence of X n’s

n{x,y} - Matches any string that contains a sequence of X to Y n’s

n{x,} - Matches any string that contains a sequence of at least X n’s


Use parentheses ( ) to apply quantifiers to entire patterns or select parts of the pattern to be used as a match.


$password = "HTMLcheatSheet123!";
if (preg_match('/^(?=.*[A-Za-z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/', $password)) {
    echo "Valid password";
} else {
    echo "Not strong enough";

Common Errors ❗

Tips to keep your code error-free.

semicolon warning Don't forget the semicolon!

  • Mismatched brackets ()
  • Incorrect quotes: " '
  • Undefined variables
  • Case sensitivity $Var$var
  • Incorrect function calls that does not exist or with incorrect parameters.

File Inclusion Errors

Using include or require with an incorrect file path. Use absolute paths or ensure relative paths are correct.

SQL Injection

Failing to sanitize user inputs can lead to SQL injection attacks. Use prepared statements and parameterized queries.

Error Handling

Use try-catch blocks and implementing proper error handling mechanisms.

Incorrect Array Usage

Check if array keys exist before accessing them.

Session Handling

Start sessions with session_start() and handle session variables correctly.

Output Buffering

Unintentional output before headers are sent can cause "headers already sent" errors. Use output buffering or ensure no output before header() calls.

Scope Issues

Variable scope misunderstandings, such as trying to access a variable outside its defined scope. Use global keyword or pass variables as function arguments.

Misconfigured php.ini

Incorrect settings in the php.ini file can lead to various issues. Ensure configuration settings are appropriate for your environment.

Deprecated Features

Using deprecated functions or features that may be removed in future PHP versions. Refer to the latest PHP documentation.

Incorrect Timezone Configuration

Set the default timezone using date_default_timezone_set().

Missing or Incorrect Encoding

Ensure correct character encoding is used, especially with multibyte strings.

Memory Limit Issues

Increase memory limit in php.ini or optimize code to use less memory.

Best Practices to Avoid Common PHP Errors

  • Use Error Reporting: Enable error reporting during development using error_reporting(E_ALL) and ini_set('display_errors', 1).
  • Code Reviews: Regular code reviews can catch errors early.
  • Testing: Write unit tests and integration tests to cover different code paths.
  • Documentation: Keep your code well-documented for easier maintenance and understanding.
  • Stay Updated: Keep up with the latest PHP versions and best practices.

PHP Filters ⚗️

Used to validate and filter data that is coming from insecure sources like user input.
    // Define filters
    $filters = array(
        'email' => FILTER_VALIDATE_EMAIL,  
// Validate email address and optionally, more filters
    // Apply filters to $_POST data
    $sanitized_inputs = filter_input_array(INPUT_POST, $filters);
    // Check if email is valid
    if ($sanitized_inputs['email'] === false) {
        echo "Invalid email address!";
    } else {
        // Use the sanitized input
        $email = $sanitized_inputs['email'];
        echo "Valid email address: " . $email;

Filter Functions

  • filter_has_var() - To check if a variable of the specified type exists
  • filter_id() -  Returns the ID belonging to a named filter
  • filter_input() - Retrieves a specified external variable by name and optionally filters it
  • filter_input_array() - Pulls external variables and optionally filters them
  • filter_list() -  Returns a list of all supported filters
  • filter_var_array() -  Gets multiple variables and optionally filters them
  • filter_var() -  Filters a variable with a specified filter

Filter Constants

  • FILTER_VALIDATE_BOOLEAN - Validates a boolean
  • FILTER_VALIDATE_EMAIL - Certifies an e-mail address
  • FILTER_VALIDATE_FLOAT - Confirms a float
  • FILTER_VALIDATE_INT - Verifies an integer
  • FILTER_VALIDATE_IP - Validates an IP address
  • FILTER_VALIDATE_REGEXP - Confirms a regular expression
  • FILTER_SANITIZE_EMAIL - Removes all illegal characters from an e-mail address
  • FILTER_SANITIZE_ENCODED - Removes/Encodes special characters
  • FILTER_SANITIZE_MAGIC_QUOTES - Applies addslashes()
  • FILTER_SANITIZE_NUMBER_FLOAT - Removes all characters, except digits, +- and .,eE
  • FILTER_SANITIZE_NUMBER_INT - Gets rid of all characters except digits and + –
  • FILTER_SANITIZE_SPECIAL_CHARS - Removes special characters
  • FILTER_SANITIZE_FULL_SPECIAL_CHARS - Converts special characters to HTML entities
  • FILTER_SANITIZE_STRING - Removes tags/special characters from a string, same as: FILTER_SANITIZE_STRIPPED
  • FILTER_SANITIZE_URL - Rids all illegal characters from a URL
  • FILTER_UNSAFE_RAW - Do nothing, optionally strip/encode special characters
  • FILTER_CALLBACK - Call a user-defined function to filter data

Date and Time 📅

Working with date and time in PHP involves several useful functions from the date and DateTime classes
// Get current timestamp
$currentTimestamp = time();
// Format and display current date and time
echo "Current timestamp: " . $currentTimestamp . "<br>";
// Format date using date() function
echo "Current date: " . date("Y-m-d") . "<br>";
echo "Current time: " . date("H:i:s") . "<br>";
// Format date and time with specific timezone
echo "Current date and time in New York: " . date("Y-m-d H:i:s");


  • d - Days from 01 to 31
  • j - Days 1 to 31
  • D - Mon through Sun
  • l - Sunday through Saturday
  • N - 1 (for Mon) through 7 (for Sat)
  • w - 0 (for Sun) through 6 (for Sat)
  • m - Months, 01 through 12
  • n - Months, 1 through 12
  • F - January through December
  • M - Jan through Dec
  • Y - Four digits year (e.g. 2018)
  • y - Two digits year (e.g. 18)
  • L - Defines whether it’s a leap year (1 or 0)
  • a - am and pm
  • A - AM and PM
  • g - Hours 1 through 12
  • h - Hours 01 through 12
  • G - Hours 0 through 23
  • H - Hours 00 through 23
  • i - Minutes 00 to 59
  • s - Seconds 00 to 59


Hover your mouse for explanation:

checkdate, date_add, date_create_from_format, date_create, date_date_set, date_default_timezone_get, date_default_timezone_set, date_diff, date_format, date_get_last_errors, date_interval_create_from_date_string, date_interval_format, date_isodate_set, date_modify, date_offset_get, date_parse_from_format, date_parse, date_sub, date_sun_info, date_sunrise, date_sunset, date_time_set, date_timestamp_get, date_timestamp_set, date_timezone_get, date_timezone_set, date, getdate, gettimeofday, gmdate, gmmktime, gmstrftime, idate, localtime, microtime, mktime, strftime, strptime, strtotime, time, timezone_abbreviations_list, timezone_identifiers_list, timezone_location_get, timezone_name_from_abbr, timezone_name_get, timezone_offset_get, timezone_open, timezone_transitions_get, timezone_version_get
Apply CSS

Online PHP Cheat Sheet

Free online interactive PHP cheat sheet, perfect for both beginners and experienced programmers. Refresh your knowledge of PHP syntax and access the most commonly used code snippets at your fingertips. Download the PDF version here.

php cheat sheet screenshot

PHP (Hypertext Preprocessor) is a powerful and widely-used server-side scripting language designed for web development. Whether you're a beginner learning the basics or an experienced developer building complex applications, this PHP cheat sheet provides a quick reference to essential syntax, functions, and best practices. From variable handling and control structures to database interactions and advanced features like object-oriented programming, this cheat sheet covers fundamental concepts and practical examples to help you write efficient, secure, and maintainable PHP code. Use it to streamline your development process, troubleshoot issues, and deepen your understanding of PHP's capabilities.

The syntax-highlighted code snippets in this PHP Cheat Sheet were created with colorful template.

Make sure you save this link to help your next project.