PHP Cheat Sheet

Our PHP cheat sheet aims to help anyone trying to get proficient in or improve their knowledge of PHP. The programming language is among the most popular in web development. It’s in the heart of WordPress, the world’s most popular CMS, and also forms the base of other platforms like Joomla and Drupal. (Don’t miss our comparison of the three.)

Aside from that, PHP is an Open Source and thus free to use. Since its inception in 1995, it has had several releases. The latest version, PHP 7.4, came out in December 2021.

PHP is a server-side language, meaning that it executes on the server, not in the user’s browser (as opposed to, for example, Javascript). PHP scripts produce HTML which is then passed on to the browser for interpretation. Consequently, the user doesn’t see the code itself but only the result.

php cheat sheet

By GgiaEsquema-proxy-internet.svg: Randomicc [CC BY-SA 3.0], from Wikimedia Commons

The programming language is relatively easy to learn for beginners, but it also offers a lot of advanced possibilities for veteran programmers.

For that reason, the following PHP cheat sheet is suitable for you no matter where you are in your journey. It covers the most important PHP concepts and functions and acts as a quick reference guide for those using PHP for web development.

We have a lot to cover, so let’s get right into it. If that’s not enough for you, we also have cheat sheets for HTML, CSS, and jQuery as well as the aforementioned Javascript.

PHP Cheat Sheet

PHP Cheat Sheet – The Basics

We are starting off with the basics – how to declare PHP in a file, write comments, and output data.

Including PHP in a File

PHP files end in .php . Besides PHP itself, they can contain text, HTML, CSS, and JavaScript. In order for a browser to recognize PHP, you need to wrap it in brackets: . Consequently, you can execute PHP on a page:

Writing Comments

Like many other languages, PHP also has the ability to add comments. This is important for annotating your code for human readers but in a way that the browser doesn’t try to execute it. In PHP, you have several ways for that:

A common example of the use of comments is WordPress theme headers:

/* Theme Name: Twenty Seventeen Theme URI: https://wordpress.org/themes/twentyseventeen/ Author: the WordPress team Author URI: https://wordpress.org/ Description: Twenty Seventeen brings your site to life with header video and immersive featured images. With a focus on business sites, it features multiple sections on the front page as well as widgets, navigation and social menus, a logo, and more. Personalize its asymmetrical grid with a custom color scheme and showcase your multimedia content with post formats. Our default theme for 2017 works great in many languages, for any abilities, and on any device. Version: 1.5 License: GNU General Public License v2 or later License URI: https://www.gnu.org/licenses/gpl-2.0.html Text Domain: twentyseventeen Tags: one-column, two-columns, right-sidebar, flexible-header, accessibility-ready, custom-colors, custom-header, custom-menu, custom-logo, editor-style, featured-images, footer-widgets, post-formats, rtl-language-support, sticky-post, theme-options, threaded-comments, translation-ready This theme, like WordPress, is licensed under the GPL. Use it to make something cool, have fun, and share what you've learned with others. */

Outputting Data

In PHP, data is commonly output using echo or print . For example, the title of this blog post might be displayed on a page like this:

PHP Cheat Sheet"; ?>

The two commands echo and print are pretty much the same. The only difference is that the former has no return value and can take several parameters, while the latter has a return value of 1 and can only take one argument.

An important note: Like all other PHP commands, functions echo and print are not case sensitive. That means that when you write ECHO , EcHo , eCHO or any other variation, they will continue to work. As you will learn further on, that doesn’t apply to everything.

Writing PHP Functions

Functions are shortcuts for commonly used chunks of code. They make programming much easier because you don’t have to re-use long code snippets. Instead, you create them once and use the shortcuts when you need them.

It’s possible to create your own PHP functions but there also many built into the programming language. Much of this PHP cheat sheet is devoted to that.

The basic syntax to create a function:

function NameOfTheFunction() < //place PHP code here >

Quick explanation: the first part is the function of a name (reminder: function names are not case sensitive). After that, everything between the curly braces is what the function does when called.

Variables and Constants

Similarly to most other programming languages, PHP lets you work with variables and constants. These are pieces of code that store different kinds of information.

Defining Variables

To do anything with variables, you first need to define them. In PHP, you denote a variable using the $ sign and assign its value using = . A typical example:

A few important points:

Types of Data

Variables can take on different types of data:

There is no need to declare PHP variables in a certain way. They automatically take on the type of data they contain.

Variable Scope

Variables can be available in different scopes, meaning the part of a script you can access them. This can be global, local and static.

Any variable declared outside of a function is available globally. That means it can be accessed outside of a function as well.

If you declare a variable inside a function, it will have a local scope. The consequence is that it can only be accessed within that function.

A way around this is to prepend a local variable with global . That way, it becomes part of the global scope.

function myFunction()

In both cases, the variable becomes part of the $GLOBALS variable mentioned below.

Finally, it’s also possible to add static in front of a local variable. That way, it won’t be deleted after its function is executed and can be reused.

Predefined Variables

PHP also comes with a number of default variables called superglobals. That’s because they are accessible from anywhere, regardless of scope.

Variable-Handling Functions

Aside from that, there are a whole bunch of functions to work with variables:

Constants

Aside from variables, you can also define constants which also store values. In contrast to variables their value can not be changed, it’s locked in.

In PHP you can define a constant:

define(name, value, true/false)

The first is the name, the second the constant’s value and the third parameter whether its name should be case sensitive (the default is false).

Constants are useful since they allow you to change the value for an entire script in one place instead of having to replace every instance of it. They are also global in nature, meaning they can be accessed from anywhere.

Aside from user-defined constants, there also a number of default PHP constants:

PHP Arrays – Grouped Values

Arrays are a way to organize several values in a single variable so that they can be used together. While functions are for blocks of code, arrays are for the values – a placeholder for larger chunks of information.

In PHP there are different types of arrays:

Declaring an Array in PHP

Arrays in PHP are created with the array() function.

Array keys can either be strings or integers.

Array Functions

PHP offers a multitude of default functions for working with arrays:

PHP Strings

In programming, speech strings are nothing more than text. As we have settled earlier, they are also a valid value for variables.

Defining Strings

In PHP there are several ways to define strings:

Note: Strings can contain variables, arrays, and objects.

Escape Characters

String Functions

PHP Operators

Operators allow you to perform operations with values, arrays, and variables. There are several different types.

Arithmetic Operators

Your standard mathematic operators.

Assignment Operators

Besides the standard assignment operator ( = ), you also have the following options:

Comparison Operators

Logical Operators

Bitwise Operators

Error Control Operator

You can use the @ sign to prevent expressions from generating error messages. This is often important for security reasons, for example, to keep confidential information safe.

Execution Operator

PHP supports one execution operator, which is `` (backticks). These are not single-quotes! PHP will attempt to execute the contents of the backticks as a shell command.

Increment/Decrement Operators

String Operators

Loops in PHP

Loops are very common in programming. They allow you to run through the same block of code under different circumstances. PHP has several different ones.

For Loop

This type goes through a block of code a specified number of times:

for (starting counter value; ending counter value; increment by which to increase) < // code to execute goes here >

Foreach Loop

A loop using foreach runs through each element in an array:

foreach ($InsertYourArrayName as $value) < // code to execute goes here >

While Loop

Loops through a block of code as long as a specified condition is true.

while (condition that must apply) < // code to execute goes here >

Do…While Loop

The final PHP loop runs a code snippet once, then repeats the loop as long as the given condition is true.

do < // code to execute goes here; >while (condition that must apply);

Conditional Statements

If/else statements are similar to loops. They are statements for running code only under certain circumstances. You have several options:

If Statement

Executes code if one condition is true.

if (condition) < // code to execute if condition is met >

If…Else

Runs a piece of code if a condition is true and another if it is not.

if (condition) < // code to execute if condition is met >else < // code to execute if condition is not met >

If…Elseif…Else

Executes different code snippets for more than two conditions.

if (condition) < // code to execute if condition is met >elseif (condition) < // code to execute if this condition is met >else < // code to execute if none of the conditions are met >

Switch Statement

Selects one of several blocks of code to execute.

switch (n) < case x: code to execute if n=x; break; case y: code to execute if n=y; break; case z: code to execute if n=z; break; // add more cases as needed default: code to execute if n is neither of the above; >

Working with Forms in PHP

PHP is often used for handling web forms. In particular, the aforementioned $_GET and $_POST help to collect data sent via a form. Both are able to catch values from input fields, however, their usage differs.

Using GET vs POST

GET collects data via URL parameters. That means all variable names and their values are contained in the page address.

The advantage of this is that you’re able to bookmark the information. Keep in mind that it also means that the information is visible to everyone. For that reason, GET is not suitable for sensitive information such as passwords. It also limits the amount of data that can be sent in ca 2000 characters.

POST, on the other hand, uses the HTTP POST method to pass on variables. This makes the data invisible to third parties, as it is sent in the HTTP body. You are not able to bookmark it.

With POST, there are no limits to the amount of information you can send. Aside from that, it also has advanced functionality and is therefore preferred by developers.

Form Security

The most important issue when it comes to web forms is security. If not set up properly, they are vulnerable to cross-scripting attacks. The hackers add scripts to unsecured web forms to use them for their own purpose.

PHP also offers tools to thwart those attacks, namely:

You will notice that we have encountered all of these functions in the previous section on strings. When you include them in the script that collects the form data, you can effectively strip harmful scripts of the characters they need for functioning, rendering them unusable.

Required Fields, Error Messages and Data Validation

Aside from that, PHP is able to define required fields (you can’t submit the form without filling them out), display error messages if some information is missing and to validate data. We have already talked about the necessary tools to do so.

For example, you can simply define variables for your form fields and use the empty() function to check if they have values. After that, create a simple if/else statement to either send the submitted data or output an error message.

The next step is to check the submitted data for validity. For that, PHP offers a number of filters such as FILTER_VALIDATE_EMAIL to make sure a submitted email address has the right format.

Regular Exprressions (RegEx)

Syntax

RegEx Functions

Returns 1 if the pattern was found in the string and 0 if not

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

Returns a new string where matched patterns have been replaced with another string

RegEx Modifiers

Performs a case-insensitive search

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

Enables correct matching of UTF-8 encoded patterns

RegEx 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

Metacharacters

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$

Find a whitespace character

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

Find the Unicode character specified by the hexadecimal number xxxx

Quantifiers

Matches any string that contains at least one n

Matches any string that contains zero or more occurrences of n

Matches any string that contains zero or one occurrences of n

Matches any string that contains a sequence of X n’s

Matches any string that contains a sequence of X to Y n’s

Matches any string that contains a sequence of at least X n’s

Grouping

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

/i"; echo preg_match($pattern, $str); // Outputs 1 ?>

PHP Functions

Syntax

function functionName() < code to be executed; >functionName();

Function Arguments

"; > familyName("Hege", "1975"); familyName("Stale", "1978"); familyName("Kai Jim", "1983"); ?>

Default Argument Value

"; > setHeight(350); setHeight(); // will use the default value of 50 setHeight(135); setHeight(80); ?>

Returning values

Date and Time

Of course, PHP functions for date and time should not be missing from any PHP cheat sheet.

Date/Time Functions

Date and Time Formatting

PHP Errors

Finally, for the times that things don’t go smoothly and you need to find out where the problem lies, PHP also offers functionality for errors.

Error Functions

Error Constants

Conclusion

Knowing your way around PHP is a good idea for anyone interested in web design and web development. Especially if you want to dive deeper into the technical aspects of creating your own website.

The PHP cheat sheet above provides you with an overview of some central parts of PHP. Bookmark it as a reference or use it as a springboard to learn more about the programming language. We sincerely hope you have found it a useful resource.

If you spot any errors in this cheat sheet, please contact us – info@websitesetup.org

Website Setup is a free resource site for helping people to create, customize and improve their websites.