go top

MEGA Sale

  • Colection of 65 PHP scripts for $4.29 each

Get 65 PHP scripts in a bundle for $4.29 each!

View Offer

PHP Cheat Sheet (Updated for 2021)

by Administrator /  Useful Resources

Welcome to this in-depth PHP cheat sheet. Below, we will list the most important concepts and functions of PHP as a reference for beginners and advanced users alike. 

If you’re a beginner, PHP is a server-side programming language. That means it is processed on the server, not in the user browser like other markup. It can produce HTML code that is then sent to and displayed by a browser.

But why should you care about learning PHP in the first place?

For one, it’s one of the most popular programming languages out there. It’s the main technology behind WordPress, the most popular CMS in the world, and finds its use in many other places like Magento, Facebook, and app development.

However, one of PHP’s main benefits is that you can use it to create dynamic web pages. That means HTML pages filled in with information that has been stored in a database. This allows you, for example, to use  PHP in order to display different content in the same design. In fact, this is how most of the PHP-based CMSs work.

Finally, the PHP programming language is open source and thus free to use. It’s also well maintained and relatively beginner-friendly as it’s easy to learn. At the same time, it’s powerful and you can do a lot with it. 

All these should be enough reason for at least getting acquainted with this popular programming language. So, let’s get right into the PHP cheat sheet.

Basic PHP Concepts

As the first step, let’s talk about some basics.

How to Write PHP

In order for PHP to be processed, you need to mark it for the browser as such. For that, PHP code typically resides inside a file that has .php as its ending, such as index.php.

However, as PHP files can also contain other content such as HTML, CSS, or JavaScript, you additionally need to wrap your code in PHP brackets. It looks like this:

<div>
    <?php
 
    // PHP code goes here
 
    ?>
</div>

This way, any browser can recognize PHP markup and avoid any errors during processing.

Commenting Your Code

Another important basic is the ability to add comments in PHP. This allows you to document your code (that is, to leave explanations for yourself or others) without having the browser try to process your comments, resulting in a glitch. In fact, commenting is a very typical feature of all programming languages.

In PHP, you have several options to include comments:

  • // or # – For comments that are only in one line.
  • /*...*/ – Use these to bracket comments that go over several lines. Everything in between /* and */ won’t execute in the browser.
<?php
 
// This is a PHP single-line comment
 
# This is a single-line comment as well
 
/*
    And here’s how you can use multi-line comments
*/
 
?>

Outputting Data on the Page

In PHP, to have data show up on the page, the most common methods are echo and print. Here’s what that typically looks like:

<?php
 
    echo "<p>This will appear on the page</p>";
 
?>

But is there a difference between echo and print? And when should you use either?

Both methods are pretty similar in how they work. However, the distinction is that echo has no return value and can take on several parameters. It’s also slightly faster.In contrast, print has a return value of 1 and only takes one argument.

By the way, operator words like echo, print, or if and else (more on that below) are case insensitive. This means you can write eCHO or PrInT if you want, it will still work. Yet, as you will soon see, this doesn’t apply to everything in PHP. On top of that, it’s good practice to stick with one case to make your code more legible.

Finally, as you can see in the last example above, you need to end every PHP statement with a semicolon (;). Otherwise, the browser will assume that it continues into the next line, which can lead to a lot of errors.

Working With Functions

Functions are an integral part of PHP. A function is basically a stand-in for a larger chunk of code. Setting them up allows you to re-use code snippets without having to post them in their entirety every time.

PHP has a lot of functions built in and you will find many of them listed in this cheat sheet. In addition, you can also create your own functions. It’s actually pretty easy and the basic syntax looks like this:

<?php
 
function ShowHowToUseFunctions() {
 
  //PHP code goes here
 
}
 
?>

First, you have the function keyword that lets you create custom functions (also known as user-defined functions). The next part is the name of the function. And everything that you place in between the curly brackets is the code that will execute whenever the function is called.

To call a function, simply type the function name followed by brackets:

<?php
 
ShowHowToUseFunctions();
 
?>

Simply place the call anywhere in your code (including the semicolon, of course) to execute the function you set up earlier.

Note that function names are written in CamelCase/camelCase, with the first letter of every new word capitalized. It’s up to you whether you want to capitalize the first letter as well. Function names also typically start with a verb that describes what the function does.

Including Files

In PHP, it’s possible to include/call files into other files to load their content on screen. This happens very often when creating web pages where different parts, like the header or footer are set up as individual files.

<?php
 
include 'header.php';
 
    //Page code goes here
 
include 'footer.php';    
 
?>

You have two ways of calling on external files, either via include as above or through require.

<?php
 
require 'header.php';
 
?>

What's the difference? When using include, if a file fails to load, the rest of the page will still keep executing. On the other hand, with require, the loading process will stop right then and there if the external file is not available.

There are also the include_once and require_once statements, which do basically the same thing as their counterparts above. The only difference is that if a file was included/required this way once, it won’t be included again via either of these statements.

Variables and Constants

PHP allows you to work with variables and constants. These are pieces of code that can store different kinds of information and are a very common part of programming languages. As you will see below, variables usually contain much more complex data than constants.

How to Define a Variable in PHP

In order to use a variable, you first need to define it. You can do that by creating a name preceded with $ and then giving it a value via =. After that, you can use the variable in your code. Here’s what that looks like:

<?php
 
$blog_post_title = 'PHP Cheat Sheet';
 
$word_count = 7317;
 
echo "This $blog_post_title has $word_count words.";
 
?>

Defining variables in PHP is as easy as that. There are only a few more things you need to know about PHP variables before we move on: 

  • They need to start with a letter or underscore (which is _) and can only contain alphanumeric characters, meaning numbers, letters, and the aforementioned underscore.
  • Unlike PHP functions and commands, variables are case sensitive. That means $ExampleVariable and $examplevariable are regarded as two different things.
  • If your variable is made up of several words, it is common practice to either write them $your_variable (aka snake case) or in the aforementioned CamelCase/camelCase.

What Kind of Data Can Variables Contain?

Variables can store different types of information:

  • Integers – These are whole numbers between -2,147,483,648 and 2,147,483,647. They must have at least one digit (0 is also an option) and can not have a decimal point. An integer can be in decimal, hexadecimal, or octal form.
  • Floats – This means numbers with a decimal point or in exponential form, e.g. 2.467.
  • Strings – That’s the name programming languages use for text. More on that soon.
  • Boolean values – Meaning true/false statements.
  • Arrays – Variables that store several values. We will further discuss them below in the PHP cheat sheet.
  • Objects – Objects store both data and the information on how to process it.
  • Resources – This means references to functions and resources outside of PHP.
  • NULL – This means the variable doesn’t have any value at all.

Variables and Scope

Scope is another thing you will hear about often when learning PHP and other programming languages. It means the context in which something is defined and available. The scope of variables can either be global, local, or static.

A variable has global scope when you define it outside of any function. In that case, it’s possible to access it outside of a function as well.

<?php
 
$blog_post_title = 'PHP Cheat Sheet'; //This is a global variable
 
echo "The title of this article is $blog_post_title";
 
?>

Variables declared inside of a function have local scope. That means they are different from the globally declared variable, even if they have the same name. You can only access global variables within a function if you prepend them with global, clarifying which one you’re aiming at.

<?php
 
$blog_post_title = 'PHP Cheat Sheet'; //This is a global variable
 
function UseGlobalVariable() {
 
    global $blog_post_title; //This would not work without the "global" keyword
   
    echo "The title of this article is $blog_post_title";
 
}
 
UseGlobalVariable();
 
?>

You can also put static in front of a variable. While these are local in scope, static variables do not lose their value after being processed. They are typically used in functions that are repeatedly called (e.g. recursive functions) in order to preserve values when a function exits.

Built-in Variables

PHP also has a few variables built in. Because these are accessible from anywhere, independent of scope, they are also called superglobals. Among them are:

  • $GLOBALS – Lets you access global variables from any place inside a PHP script.
  • $_SERVER – Contains the locations of headers, paths, and scripts.
  • $_GET – Allows you to collect data sent in the URL or submitted via an HTML form.
  • $_POST – Its function is to collect data from HTML forms and to pass variables.
  • $_REQUEST – Also gathers data from HTML form submissions.

For example, here is the function from above rewritten using $GLOBALS:

<?php
 
$blog_post_title = 'PHP Cheat Sheet';
 
function UseGlobalVariable() {
    
    echo "The title of this article is " . $GLOBALS['blog_post_title'];
    
}
 
UseGlobalVariable();
 
?>

By using $GLOBALS and other predefined variables, you’ll be able to access data across your entire PHP project, other files, and more.

Functions to Handle Variables

In addition, PHP offers a wide range of built-in functions to work with variables: 

  • boolval – Retrieves the boolean value of a variable.
  • debug_zval_dump – Produces an internal Zend value as a string representation.
  • empty – Check for whether a variable is empty or not.
  • floatval – Retrieve the float value of a variable (see also doubleval).
  • get_defined_vars – Gives you an array of all defined variables.
  • get_resource_type – Returns the resource type.
  • gettype – Retrieves the type of a variable.
  • import_request_variables – Import GET/POST/Cookie variables to the global scope.
  • intval – Lets you find the integer value of a variable.
  • is_array – Confirms if a variable is an array.
  • is_bool – Finds out whether a variable is a boolean value.
  • is_callable – Verifies whether it’s possible to call the contents of a variable in the form of a function.
  • is_countable – Check for whether the contents of a variable can be counted.
  • is_float – Is the variable type float? Alternative functions are is_double and is_real.
  • is_int – Tests a variable if it is an integer. You can also use is_integer and is_long.
  • is_iterable – If a variable is an iterable value, you can test with this.
  • is_null – Looks for whether a variable’s value is NULL.
  • is_numeric – You can find out if a variable is a number or a numeric string with this function.
  • is_object – Checks if a variable is an object.
  • is_resource – Verifies a variable as a resource or not.
  • is_scalar – Finds out if a variable is a scalar.
  • is_string – PHP function to determine the type of a variable as a string.
  • isset – Checks for whether a variable has been set and its value is not NULL.
  • print_r – Puts out information about a variable that is humanly readable.
  • serialize – Produces a representation of a value that can be stored.
  • settype – Sets the type of a variable.
  • strval – Fetches a variable’s string value.
  • unserialize – Creates a PHP value from a stored representation.
  • unset – Unsets a variable, basically the opposite of =.
  • var_dump – Dumps information about a variable.
  • var_export – Produces or returns a string representation of a variable that can be parsed.

Constants

Another PHP element that can store information are constants. However, in contrast to variables, their value is set and can not be changed (you might even say, it’s constant). 

Here’s how to define a constant in PHP:

<?php
 
define(name, value, true/false);
 
?>

Entering the information inside the parentheses, you can give the constant a name, define its value, and also determine whether it should be case insensitive or not (by default, this is set to false).

<?php
 
define("greeting", "Oh, hi there!", true);
 
echo greeting;
 
echo GREETING; //This will only work with the last parameter set to "true"
 
?>

What are constants typically used for?

For example, they allow you to change the value for entire scripts in one central place. Constants are also part of global scope, so you can access them from wherever you want.

Besides the possibility to define constants yourself, PHP also comes with a number of pre-defined constants:

  • __LINE__ – The number of the current line inside of a file.
  • __FILE__ – Contains the full path and filename of the file.
  • __DIR__ – The file’s directory.
  • __FUNCTION__ – Name of the function.
  • __CLASS__ – Class name including the namespace it was declared in.
  • __TRAIT__ – The trait name (also including the namespace).
  • __METHOD__ –  The class method name.
  • __NAMESPACE__ – Name of the current namespace.

Arrays

Arrays are pretty much for values what functions are for code blocks: a way to pack more than one thing into a single placeholder in order to use them together. They can contain values or keys paired with values. Here are two examples:

<?php
 
$fruit_salad = array("apple", "banana", "kiwi");
 
$personal_data = array(
 
    "first_name" => "John";
    "last_name" => "Smith";
    "age" => 42;
 
);
 
?>

In the case of $personal_data, the "first_name" and "last_name" are keys. Following the => symbols are the values they’re paired with.

Keys can either be strings or integers (so, text and whole numbers), values can be of any type. PHP knows three different kinds of arrays, indexed (meaning, they have a numeric index, like the first example above), associative (keys are named and have a value assigned, like in the second example), and multidimensional (these contain one or several other arrays).

You can create arrays with the array() function like seen above. It’s also possible to use the short array syntax with square brackets:

<?php
 
$fruit_salad = ["apple", "banana", "kiwi"];
 
?>

In addition, you can access individual values inside of arrays by including their location index (starting from 0) in square brackets:

<?php
 
echo "This is " . $personal_data[0] . " " . $personal_data[1] . ", he is " . $personal_data[2] . " years old.";
 
?>

Finally, it’s also possible to use very similar syntax to add more elements to an array.

<?php
 
$fruit_salad = ["apple", "banana", "kiwi"];
 
$fruit_salad[] = "strawberry";
 
?>

After adding the last line, the array would look like this:

<?php
 
$fruit_salad = ["apple", "banana", "kiwi", "strawberry"];
 
?>

Array Functions

PHP comes with a lot of built-in functionality for the handling of arrays:

  • array_change_key_case – Transforms all the keys in an array to uppercase or lowercase.
  • array_chunk – Use this to split an array into chunks of a defined length.
  • array_column – Pulls the values from a single column inside an array.
  • array_combine – Combines the keys from one array and the values from another into a single new array.
  • array_count_values – Tallies all available values in an array.
  • array_diff – Compares arrays, returns their difference (values only).
  • array_diff_assoc –Like array_diff but returns values and keys.
  • array_diff_key – Same as the above but returns keys only.
  • array_diff_uassoc – Compares arrays (both keys and values) with a user callback function.
  • array_diff_ukey – Like array_diff_uassoc but compares keys only.
  • array_fill – Fills an array with values.
  • array_fill_keys – Fills an array with values, specifying keys.
  • array_filter – Filters an array’s elements through a callback function.
  • array_flip – Exchanges all the keys inside an array with their associated values.
  • array_intersect – Compares arrays and returns their matches (values only).
  • array_intersect_assoc – Same as array_intersect but returns both keys and values.
  • array_intersect_key – Like the above but returns keys only.
  • array_intersect_uassoc – Compare arrays via a user-defined callback function (keys and values).
  • array_intersect_ukey – Like array_intersect_uassoc but compares only keys.
  • array_key_exists – Checks if a named key exists in an array, alternative: key_exists.
  • array_keys – Returns all keys in an array or a subset.
  • array_map – Applies a callback to the elements in an array.
  • array_merge – Merge one or more arrays.
  • array_merge_recursive – Merge one or several arrays recursively.
  • array_multisort – Sorts multiple or multi-dimensional arrays.
  • array_pad – Inserts a set number of items (with a specific value) into an array.
  • array_pop – Permanently removes the last element from the end of an array.
  • array_product – Calculates the product of all values inside an array.
  • array_push – Pushes one or more elements towards the end of an array.
  • array_rand – Picks out one or several random entries out of an array.
  • array_reduce – Trims the array to a single string via a user-defined function.
  • array_replace – Replaces elements in the first array with values from following arrays.
  • array_replace_recursive – Same as array_replace but works recursively.
  • array_reverse – Reverses the order of an array and returns it.
  • array_search – Searches the array for a specified value and returns the first matching key if successful.
  • array_shift – Shifts an element from the beginning of an array.
  • array_slice – Extracts a slice of an array.
  • array_splice – Removes a portion of an array and (optionally) replaces it.
  • array_sum – Calculates the sum of all the values in an array.
  • array_udiff – Compares several arrays and returns the difference via a user function (values only).
  • array_udiff_assoc – Compares arrays and returns the difference using a user function (keys and values).
  • array_udiff_uassoc – Compares arrays and returns the difference using two user functions (values and keys).
  • array_uintersect – Compares arrays and returns their matches via a user function (values only).
  • array_uintersect_assoc – Compares the keys and values of arrays and returns their matches via a user function.
  • array_uintersect_uassoc – Compares arrays and returns their matches via two user functions (keys and values).
  • array_unique – Removes values that are duplicate from inside an array.
  • array_unshift – Adds one or several elements to the start of an array.
  • array_values – Returns all the values of an array.
  • array_walk – Applies a user function to every element in an array.
  • array_walk_recursive – Same as array_walk but working recursively.
  • arsort – Sorts an associative array in descending order of the values.
  • asort – Sorts the values of an associative array in ascending order.
  • compact – Creates an array containing variables and their values.
  • count – Count all the elements inside an array, alternative: sizeof.
  • current – Returns the current element inside an array, alternatively you can use pos.
  • each – Returns the current key and value pair from an array.
  • end – Sets the internal pointer in an array to its last element.
  • extract – Imports variables from an array into the current symbol table.
  • in_array – Checks an array if a specified value exists.
  • key – Retrieves a key from an array.
  • krsort – Sorts an associative array by key (in reverse order).
  • ksort – Arranges an associative array by key.
  • list – Assigns variables as if they were an array.
  • natcasesort – Sorts an array using a "natural order" algorithm independent of case.
  • natsort – Sorts an array using a "natural order" algorithm.
  • next – Advances the internal pointer of an array.
  • prev – Moves the internal array pointer backward.
  • range – Creates an array from a range of elements.
  • reset – Moves the internal array pointer to the first element.
  • rsort – Sorts an array in reverse order.
  • shuffle – Shuffles an array.
  • sort – Sorts an indexed array in ascending order.
  • uasort – Sorts an array according to a user-defined comparison function.
  • uksort – Arranges an array by key using a user-defined comparison function.
  • usort – Categorizes an array by value using a user-defined comparison function.

Strings

As mentioned earlier, strings is the word programmers use for pieces of text. They can also be values inside variables and arrays. On the other hand, strings themselves can contain variables, arrays, and objects.

In PHP, you can define something as a string in several ways:

  • Single quotes – Simply wrap your text in ' and PHP will know its a string. Example: <?php echo 'This is a string'; ?>.
  • Double quotes – Alternatively, you can also use " (e.g. <?php echo "This is also a string"; ?>). This has the added benefit that you can use escape characters within the string. More on that below.
  • heredoc – Begin a string with <<< and an identifier, then put the string in a new line. You can close it in another line by repeating the identifier. heredoc behaves the same way as double-quoted strings.
  • nowdoc – Same as heredoc but behaving like single quotes, meaning you can’t use escape characters.

In addition, you can combine strings using the . operator. This is called concatenation and looks like this:

<?php
 
echo "Hi," . " my name is..."; //Will output "Hi, my name is..."
 
?>

Don’t forget to add needed spaces as the operator does not do that automatically.

Escape Characters

Escape characters allow you to add special symbols, commands, and letters. In order to use them, you need to define the string that contains them with double quotes. Here are the characters available:

  • \n – Line break
  • \r – Carriage return
  • \t – Horizontal tab
  • \v – Vertical tab
  • \e – Escape
  • \f – Form feed
  • \\ – Backslash
  • \$ – Dollar sign
  • \' – Single quote
  • \" – Double quote
  • \[0-7]{1,3} – Character in octal notation
  • \x[0-9A-Fa-f]{1,2} – Character in hexadecimal notation
  • \u{[0-9A-Fa-f]+} – String as UTF-8 representation

And here’s a quick example:

<?php
 
echo "My favorite movie is \"Pirates of the Carribean.\"";
 
?>

Without using the escape characters here, the code wouldn’t be able to tell the difference between the quotation marks that set the length of the string and the ones that are part of the string itself.

String Functions

In addition to the above, here are the PHP functions you can use in association with strings: 

  • addcslashes() – Returns a string with backslashes in front of specified characters.
  • addslashes() – Returns a string with backslashes in front of characters that need escaping.
  • bin2hex() – Converts a string from ASCII characters to hexadecimal values.
  • chop() – Removes spaces or other characters from the right end of a string.
  • chr() – Returns a character from a specified ASCII value.
  • chunk_split() – Splits a string into a series of chunks.
  • convert_cyr_string() – Converts a string from Cyrillic characters to another character set.
  • convert_uudecode() – Decodes a uuencoded string.
  • convert_uuencode() – Encodes a string using uuencode.
  • count_chars() – Returns information about the number of characters in a string.
  • crc32() – Calculates a 32-bit CRC for a string.
  • crypt() – Returns a hashed (meaning encrypted) string.
  • echo() or echo '' – As already covered above, outputs one or more strings.
  • explode() – Breaks a string down into an array.
  • fprintf() – Writes a formatted string to a specified output stream.
  • get_html_translation_table() – Returns the translation table used by htmlspecialchars() and htmlentities().
  • hebrev() – Transforms Hebrew text to visual text.
  • hebrevc() – Converts Hebrew text to visual text and adds HTML line breaks.
  • hex2bin() – Opposite of bin2hex(), translates hexadecimal values to ASCII characters.
  • html_entity_decode() – Transforms HTML entities into characters.
  • htmlentities() – Turns characters into HTML entities.
  • htmlspecialchars_decode() – Transfers special HTML entities to characters.
  • htmlspecialchars() – Turns predefined characters into HTML entities.
  • implode() – Fetches a string from the elements of an array, same as join().
  • lcfirst() – Changes the first character of a string to lowercase.
  • levenshtein() – Calculates the Levenshtein distance between two strings.
  • localeconv() – Returns information about numeric and monetary formatting for the defined locale.
  • ltrim() – Removes spaces or other characters from the left end of a string.
  • md5() – Calculates the MD5 hash (a type of encryption) of a string and returns it.
  • md5_file() – Calculates the MD5 hash of a file.
  • metaphone() – Provides the metaphone key of a string.
  • money_format() – Turns a string into a currency string.
  • nl_langinfo() – Gives specific information about the locale.
  • nl2br() – Puts HTML line breaks to each new line in a string.
  • number_format() – Formats a number including grouped thousands.
  • ord() – Returns the ASCII value of the first character of a string.
  • parse_str() – Parses a string into variables.
  • print() – Outputs one or several strings.
  • printf() – Outputs a formatted string.
  • quoted_printable_decode() – Converts a quoted-printable string to 8-bit binary.
  • quoted_printable_encode() – The other way around, from 8-bit string to a quoted-printable string.
  • quotemeta() – Returns a string with backslashes before metacharacters.
  • rtrim() – Trims whitespace or other characters from the right side of a string.
  • setlocale() – Sets locale information.
  • sha1() – Calculates a string’s SHA-1 hash.
  • sha1_file() – Computes the SHA-1 hash for a file.
  • similar_text() – Determines the similarity between two strings.
  • soundex() – Calculates the soundex key of a string.
  • sprintf() – Returns a formatted string.
  • sscanf() – Parses input from a string according to a specified format.
  • str_getcsv() – Parses a CSV string into an array.
  • str_ireplace() – Replaces specified string characters with defined replacements (case-insensitive).
  • str_pad() – Pads a string to a specified length either using spaces of defined characters.
  • str_repeat() – Repeats a string a defined number of times.
  • str_replace() – Replaces specified characters inside a string (case-sensitive).
  • str_rot13() – Applies ROT13 encoding on a string.
  • str_shuffle() – Randomly shuffles a string’s characters.
  • str_split() – Splits strings into arrays.
  • str_word_count() – Returns the number of words in a string.
  • strcasecmp() – Comparison of two strings (case insensitive).
  • strcmp() – Binary safe string comparison (case-sensitive).
  • strcoll() – Compares two strings based on locale.
  • strcspn() – Returns the number of characters found in a string before the specified characters occur.
  • strip_tags() – Removes any HTML and PHP tags from a string.
  • stripcslashes() – Opposite of addcslashes().
  • stripslashes() – Opposite of addslashes().
  • stripos() – Finds the position of where a substring first appears within a string (case insensitive).
  • stristr() – Case-insensitive version of strstr().
  • strlen() – Returns the length of a specified string.
  • strnatcasecmp() – Comparison of two strings using a "natural order" algorithm (case insensitive).
  • strnatcmp() – Same as strnatcasecmp() but case-sensitive.
  • strncasecmp() – Case-insensitive string comparison of a defined number of characters.
  • strncmp() – Same as above but case sensitive.
  • strpbrk() – Examines a string for any number of characters.
  • strpos() – Case-sensitive version of stripos().
  • strrchr() – Finds the last occurrence of a string within another string.
  • strrev() – Reverses a string.
  • strripos() – Seeks the position of the last occurrence of a string’s substring (case insensitive).
  • strrpos() – Same as strripos() but case sensitive.
  • strspn() – Returns the number of specified characters in a string.
  • strstr() – Case-sensitive search for the first occurrence of a string inside another string.
  • strtok() – Splits a string into chunks.
  • strtolower() – Converts all of a string’s characters to lowercase.
  • strtoupper() – Same but transforms characters to uppercase letters.
  • strtr() – Translates defined characters in a string.
  • substr() – Returns a specified part of a string.
  • substr_compare() – Compares two strings from a defined position up to a certain length, optionally case sensitive.
  • substr_count() – Calculates the number of times that a substring occurs within a string.
  • substr_replace() – Replaces a substring with something else.
  • trim() – Removes space or other characters from both the left and right ends of a string.
  • ucfirst() – Transforms a string’s first character to uppercase.
  • ucwords() – Turns the first character of every word in a string into uppercase.
  • vfprintf() – Writes a formatted string to a specified output stream.
  • vprintf() – Outputs a formatted string.
  • vsprintf() – Writes a formatted string to a variable.
  • wordwrap() – Shortens a string to a specified number of characters.

PHP Operators

Operators are called this way because they enable you to perform operations with values, arrays, and variables. PHP has several different types of them.

Arithmetic Operators

These you should mostly remember from elementary school:

  • + – Addition
  • - – Subtraction
  • * – Multiplication
  • / – Division
  • % – Modulo (the remainder of a value divided by another)
  • ** – Exponentiation

Assignment Operators

The standard assignment operator is =, which we have already seen in action for variables. However, you can combine the standard = operator with other operators to perform more complex operations. You have the following options:

  • += – a += b means the same as a = a + b
  • -= – a -= b means the same as a = a – b
  • *= – a *= b means the same as a = a * b
  • /= – a /= b means the same as a = a / b
  • %= – a %= b means the same as a = a % b

Here’s an example for how to use the above:

<?php
 
$number = 3;
 
$number += 4; //Now $number has a value of 7
 
?>

Comparison Operators

Operators of this kind allow you to make comparisons between elements, for example, in order to create conditions that need to be met in order for a function to trigger.

  • == – Equal
  • === – Identical
  • != – Not equal
  • <> – Not equal
  • !== – Not identical
  • < – Less than
  • > – Greater than
  • <= – Less than or equal to
  • >= – Greater than or equal to
  • <=> – Less than, equal to, or greater than

Logical Operators

In addition to the above, logical operators help you include additional syntax. 

  • and – And
  • or – Or
  • xor – Exclusive or, meaning if only one condition evaluates to TRUE but not both
  • ! – Not
  • && – And
  • || – Or

Bitwise Operators

These allow you to evaluate and manipulate bits within integers.

  • & – And
  • | – Or (inclusive or)
  • ^ – Xor
  • ~ – Not
  • << – Shift left
  • >> – Shift right

The Error Control Operator

The @ symbol is an operator that can prevent expressions from generating error messages. Doing so is often a security measure, such as to keep confidential information safe.

Execution Operator

PHP supports one execution operator, which is `` (backticks, not single quotes!). When used, PHP will try to execute the contents of the backticks as a shell command, meaning inside the system terminal. It’s the same as shell_exec().

Increment/Decrement Operators

Operators to increase and decrease the values inside variables.

  • ++$v – Increments a variable by one, then returns it.
  • $v++ – Returns a variable, then increments it by one.
  • --$v – Decrements a variable by one and returns it afterward.
  • $v-- – Returns the variable then decrements it by one.

String Operators

  • . – As already covered above, this operator allows you to combine two strings
  • .= – You can use this to append a string to the right of an existing string

Loops

Loops are another crucial part of PHP. A loop runs through a piece of code several times under different pre-defined circumstances. You have several options for this.

For Loop

Runs through a piece of code a defined number of times.

<?php
 
for (starting value; ending value; increment by which to increase) {
 
    // code to execute goes here
 
}
 
?>

You can also use its shorthand:

<?php
 
for (conditions):
 
    // code to execute goes here
 
endfor;
 
?>

Foreach Loop

This type of loop runs through every element of an array.

<?php
 
foreach ($array_name as $value) {
 
    // code to execute goes here
 
}
 
?>

It has a shorthand as well:

<?php
 
foreach ($array_name as $value):
 
    // code to execute goes here
 
endforeach;
 
?>

While Loop

Goes through a piece of code as long as a defined condition applies.

<?php
 
while (condition) {
 
    // code to execute goes here
 
}
 
?>

Shorthand notation also exists for this:

<?php
 
while (condition):
 
    // code to execute goes here
 
endwhile;
 
?>

Do...While Loop

The final type of loop goes through the code block at least once (even if the condition is false) and then repeats the loop as long as its conditions are met. 

<?php
 
do {
    
    // code to execute goes here
 
} while (condition);
 
?>

Typical applications for do...while loops are when you want to test something. The test will run at least once and its result will be evaluated afterwards.

Conditional Statements

Conditional statements are similar to loops. They only execute as long as their conditions are true, however, only once instead of repeatedly. Here, too, you have more than one option.

If Statement

If one condition is true, the code block is executed.

<?php
 
if (condition) {
 
    // code to execute goes here
 
}
 
?>

If...Else

This one runs one piece of code if the condition is true and another if it is not.

<?php
 
if (condition) {
 
    // code to execute if condition is true
 
} else {
 
    // code to execute if condition is false
 
}
 
?>

If...Elseif...Else

Runs different pieces of code depending on which condition is true.

<?php
 
if (condition) {
 
    // code to execute if condition is true
 
} elseif (condition2) {
 
    // code to execute if condition2 is true
 
} else {
 
    // code to execute if none of the conditions are true
 
}
 
?>

You can add as many instances of elseif as needed.

Switch Statement

This allows you to select one of several code blocks to use if different cases are true.

<?php
 
switch (input) {
 
    case x:
        // code to execute if input=x;
        break;
 
    case y:
        // code to execute if input=y;
        break;
 
    case z:
        // code to execute if input=z;
        break;
 
    // add more cases as needed
 
    default:
        // code to execute if input is none of the above;
}
 
?>

Filters

Filters validate and filter data, including from potentially insecure sources. This often comes in handy when dealing with data submitted via forms. You can use the following filter functions and constants.

Filter Functions

  • filter_has_var() – Checks for the existence of a variable of a specified type.
  • filter_id() – Returns the ID of a named filter.
  • filter_input() – Retrieves a specified external variable by name and optionally filters it.
  • filter_input_array() – Pulls external variables with the option to filter them.
  • filter_list() – Returns a list of all supported filters.
  • filter_var_array() – Gets multiple variables, optionally filters them.
  • filter_var() – Filters a variable with a specified filter.

Filter Constants 

  • FILTER_VALIDATE_BOOLEAN – Validates a boolean.
  • FILTER_VALIDATE_EMAIL – Validates an email address.
  • FILTER_VALIDATE_FLOAT – Certifies something as a float.
  • FILTER_VALIDATE_INT – Validates an integer.
  • FILTER_VALIDATE_IP – Verifies an IP address.
  • FILTER_VALIDATE_REGEXP – Confirms something as a regular expression.
  • FILTER_VALIDATE_URL – Validates a URL.
  • FILTER_SANITIZE_EMAIL – Removes all illegal characters from an email address.
  • FILTER_SANITIZE_ENCODED – Removes/encodes special characters.
  • FILTER_SANITIZE_MAGIC_QUOTES – Applies addslashes().
  • FILTER_SANITIZE_NUMBER_FLOAT – Removes all illegal characters from a float, meaning everything except digits, +/- and optionally .,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 – Transforms special characters into HTML entities.
  • FILTER_SANITIZE_STRING – Removes tags and special characters from a string, alternative: FILTER_SANITIZE_STRIPPED.
  • FILTER_SANITIZE_URL – Rids a URL of all illegal characters.
  • FILTER_UNSAFE_RAW –Do nothing, optionally strip/encode special characters.
  • FILTER_CALLBACK – Call a user-defined function to filter data.

Date and Time

Date and time are also an important part of PHP as the programming language is often used to output them, e.g. like so:

<?php
 
echo "Today's date is " . date("Y/m/d");
 
?>

Where does that information come from? As a server-side language, PHP gets the time and date from the server that your scripts run on. You also have a number of formatting options and functions for this, discussed below.

Date and Time Formatting

Use the formatting options below to display date and time information in your preferred format.

  • d – 01 to 31
  • j – 1 to 31
  • D – Mon through Sun
  • l – Sunday through Saturday
  • N – 1 (for Mon) through 7 (for Sun)
  • 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 digit year (e.g. 2021)
  • y – Two digit year (e.g. 21)
  • 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

Date/Time Functions

In addition, you can use these functions to perform tasks related to date and time:

  • checkdate() – Checks whether a Gregorian date is valid.
  • date_add() – Adds a specific number of days, months, years, hours, minutes and/or seconds to a date object.
  • date_create_from_format() – Returns a formatted DateTime object.
  • date_create() – Creates a new DateTime object.
  • date_date_set() – Sets a new date.
  • date_default_timezone_get() – Returns the default timezone used by all functions.
  • date_default_timezone_set() – Sets the default timezone.
  • date_diff() – Calculates the difference between two dates.
  • date_format() – Returns a date formatted in a specific format.
  • date_get_last_errors() – Returns warnings or errors present in a date string.
  • date_interval_create_from_date_string() – Sets up a DateInterval from relative parts of a string.
  • date_interval_format() – Formats an interval.
  • date_isodate_set() – Sets a date according to ISO 8601 standards.
  • date_modify() – Modifies the timestamp.
  • date_offset_get() – Returns the timezone’s offset.
  • date_parse_from_format() – Returns an array with detailed information about a specified date, according to a specified format.
  • date_parse() – Returns an array with detailed information about a specified date.
  • date_sub() – Subtracts a number of days, months, years, hours, minutes and seconds from a date.
  • date_sun_info() – Returns an array containing information about sunset/sunrise and twilight beginning/end for a specified day and location.
  • date_sunrise() – The time of sunrise for a specific day and location.
  • date_sunset() – The time of sunset for a specific day and location.
  • date_time_set() – Sets the time.
  • date_timestamp_get() – Returns the Unix timestamp.
  • date_timestamp_set() – Sets the date and time based on a Unix timestamp.
  • date_timezone_get() – Returns the timezone of a given DateTime object.
  • date_timezone_set() – Sets the timezone for a DateTime object.
  • date() – Formats a local date and time.
  • getdate() – Date/time information of a timestamp or the current local date/time.
  • gettimeofday() – Returns the current time.
  • gmdate() – Lets you format a GMT/UTC date and time.
  • gmmktime() – The Unix timestamp for a GMT date.
  • gmstrftime() – Formats a GMT/UTC date and time according to locale settings.
  • idate() – Sets up a local time/date in the form of an integer.
  • localtime() – The current local time.
  • microtime() – The current Unix timestamp with microseconds.
  • mktime() – The Unix timestamp of a date.
  • strftime() – Formats a local time and/or date according to settings of the locale.
  • strptime() – Parses a time/date generated with strftime().
  • strtotime() – Changes an English textual DateTime into a Unix timestamp.
  • time() – The current time in the form of a Unix timestamp.
  • timezone_abbreviations_list() – Returns an array containing dst, offset, and the timezone name.
  • timezone_identifiers_list() – An indexed array with all timezone identifiers.
  • timezone_location_get() – Location information for a specific timezone.
  • timezone_name_from_abbr() – Returns the timezone name from an abbreviation.
  • timezone_name_get() – The name of the timezone.
  • timezone_offset_get() – The timezone offset from GMT.
  • timezone_open() – Creates a new DateTimeZone object.
  • timezone_transitions_get() – Returns all transitions for the timezone.
  • timezone_version_get() – Returns the version of the timezonedb.

Forms

PHP is often involved in collecting information from web forms. It has some specific functionality that is very helpful for that.

GET vs POST

The two main variables used to collect form data are $_GET and $_POST. They can both collect values that have been added to input fields. However, their usage is not the same. 

GET collects data from parameters that have been added to the URL. That means, variables and values show up in the web address.

https://yourshop.com/men/pants/?type=jeans

The advantage is that you can bookmark them that way and when you open the link, the parameters are automatically used. However, of course, that also means they are completely visible, which is why this method is not suitable for sensitive data like passwords or usernames. It also limits you to about 2,000 characters.

For secure data you need to use POST, which uses the HTTP POST method to pass on variables, which makes them invisible to the outside. There is also no character limit.

Form Security

Security is a central issue for web forms. You want to keep the data safe and protect yourself from outside attacks. Below are tools that PHP offers to prevent cross scripting. We have already covered them in the section about strings.

  • htmlspecialchars()
  • trim()
  • stripslashes() 

The functions above allow you to strip scripts of harmful characters that make them work. That way, they are unable to execute.

Required Fields, Error Messages, Data Validation

To further increase security, you can define required fields, display error messages, and use data validation.

How does that help?

When a field is required, it needs to be filled in so the form can be submitted. If it’s not, you can display an error message. In addition, data validation lets you check if the data is as it should be. For example, FILTER_VALIDATE_EMAIL allows you to check if a submitted email address is in the proper format.

Regular Expression (RegEx)

RegEx is a sequence of characters that define a pattern of text to search. You can use it to parse text files or find keywords in emails and web pages.

Syntax

Here’s the basic syntax of RegEx:

<?php
 
$pattern = "/searchpattern/i";
 
?>

The first is the variable you will use in a function to perform a search. The forward slashes (/) are the delimiters that mark the beginning and end of the search pattern. Inside of them is the pattern you want to look for and the i at the end is the modifier (optional, more on that below).

RegEx Functions

  • preg_match() – Returns 1 if a pattern was found in a string, 0 if not.
  • preg_match_all() – Returns the number of times a pattern was found in a string, may also be 0.
  • preg_replace() – Returns a new string in which matched patterns have been replaced with another string.

RegEx Modifiers

  • i – Performs a case-insensitive search.
  • m – Runs 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.

RegEx Patterns

  • [abc] – Looks for one character from the options between the brackets.
  • [^abc] – Searches any character that is NOT between the brackets.
  • [0-9] – Tries to find one character from the range 0 to 9.

Metacharacters

  • | – Finds a match for any of the patterns separated by | as in: apple|banana|kiwi.
  • . – Looks for just one instance of any character, for example .... will bring up any four-letter text.
  • ^ – Searches a match at the beginning of a string as in: ^Hi.
  • $ – Looks for a match at the end of the string as in: goodbye$.
  • \d – Finds a digit.
  • \s – Looks for a whitespace character.
  • \b – Searches for a match at the beginning of a word like this: \bWORD, or at the end of a word like this: WORD\b.
  • \uxxxx – Finds the Unicode character specified by the hexadecimal number xxxx.

Quantifiers

  • 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 occurrence 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.

Grouping

You can use parentheses ( ) to apply quantifiers to entire patterns. It’s also possible to select parts of the pattern to use as a match. For example, a search pattern of /I like (apples|bananas)/ will match both I like apples and I like bananas. The parentheses limit the function of | to their contents.

HTTP Functions

PHP is able to manipulate data sent from the web server to the browser and has a number of useful functions for that.

  • header() – Sends a raw HTTP header to the browser.
  • headers_list() – Returns a list of response headers that are ready to send or have already been sent.
  • headers_sent() – Checks if and where the HTTP headers have been sent to.
  • setcookie() – Defines a cookie to deliver along with the rest of the HTTP headers.
  • setrawcookie() – Defines a cookie (without URL encoding) to go along.

PHP Errors

In case something doesn’t work out as it should, PHP also has functionality to handle errors.

Error Functions

Below are built-in functions for error handling.

  • debug_backtrace() – Generates a backtrace.
  • debug_print_backtrace() – Prints a backtrace.
  • error_get_last() – Returns the last error that occurred.
  • error_log() – Sends an error message to a web server’s log, a file, or an email account.
  • error_reporting() – Specifies which PHP errors are reported.
  • restore_error_handler() – Goes back to the previous error handler function.
  • restore_exception_handler() – Reverts to the previous exception handler.
  • set_error_handler() – Specifies a user-defined function to handle script errors.
  • set_exception_handler() – Sets up an exception handler function specified by the user.
  • trigger_error() – Generates a user-level error message, alternative: user_error().

Error Constants

And here are the constants related to errors that are part of PHP’s core.

  • E_ERROR – Fatal run-time errors that cause the script to halt and can’t be recovered from.
  • E_WARNING – Non-fatal run-time errors, in which execution of the script continues.
  • E_PARSE – Compile-time parse errors (should solely be generated by the parser).
  • E_NOTICE – Run-time notices that show a possible error.
  • E_CORE_ERROR – Fatal errors during PHP initialization, like an E_ERROR in PHP core.
  • E_CORE_WARNING – Non-fatal errors while PHP starts up, similar to E_WARNING but in PHP core.
  • E_COMPILE_ERROR – Fatal compile-time errors caused by the Zend Scripting Engine.
  • E_COMPILE_WARNING – Non-fatal compile-time errors coming from the Zend Scripting Engine.
  • E_USER_ERROR – Fatal user-generated errors, set by the developer using trigger_error().
  • E_USER_WARNING – Non-fatal user-generated warning.
  • E_USER_NOTICE – User-generated notice by trigger_error().
  • E_STRICT – Suggestions by PHP to improve your code (only available when enabled).
  • E_RECOVERABLE_ERROR – Catchable fatal error caught by a user-defined handle.
  • E_DEPRECATED – Enable this to receive warnings about deprecated code.
  • E_USER_DEPRECATED – User-generated warning for deprecated code.
  • E_ALL – All errors and warnings except E_STRICT.

Final Thoughts: PHP Cheat Sheet

A PHP cheat sheet is a great thing to have in your toolbox for some quick help and an overview, both for learners and experienced users. While we can’t cover all of PHP, it does come in handy when in a bind.

Above, we have covered many of the most crucial functions, functionality, variables, constants, and more of the programming language. As a beginner, you are now ready to get started on learning and improving your PHP capabilities. If you want to do so, here are a few tips on where you can get started:

Thanks for your attention. We hope you found our PHP cheat sheet useful.

Share on:

Comments to "PHP Cheat Sheet (Updated for 2021)"

Add your comment

Captcha

    Please, be polite and helpful and do not spam or offend others! We promise you will be treated the same way!

    Log in to your account to post your comments. If you still haven't joined our community yet, you can create your FREE account now!

    Posting tip:
    If you use code in your comments, please put it in these tags [php], [sql], [css], [js] PHP code example: [php] echo date("Y-m-d"); [/php]

    Thank you,
    PHPJabbers Team