PHP Cheat Sheet: A Comprehensive Guide to Writing Efficient and Secure Code

Estimated read time 13 min read

This PHP cheat sheet is designed to provide a quick reference for developers who are new to the language or who need a quick refresher.

Introduction PHP, or Hypertext Preprocessor, is a widely-used open-source programming language that is particularly suited for web development. It can be embedded into HTML and is often used to create dynamic websites, as well as for server-side scripting.

A cheat sheet is a quick reference guide that provides a programmer with a summary of the most important and commonly used features of a programming language.

Basic Syntax

Find below the basic syntax;

Writing a PHP Script

To write a PHP script, you first need to start the script with an opening PHP tag, which is <?php. This tells the server that the following code is written in PHP. The PHP code should be written after the opening PHP tag, and it can be a simple command or a complex script.

Once the PHP code is written, it needs to be closed with a closing PHP tag, which is ?>. The closing PHP tag tells the server that the PHP code has ended.

Also Check: Web Development Companies in Los Angeles

Including PHP Code in an HTML File

PHP code can be included in an HTML file by simply adding the PHP code within the PHP tags in the HTML file. The PHP code will be executed on the server and the result will be embedded into the HTML file. This allows for dynamic content to be generated and displayed on the web page.

Using Variables

In PHP, variables are used to store values that can be used throughout the script. Variables are declared using the $ symbol, followed by the variable name. For example, $myVariable. Once a variable is declared, it can be used to store different data types such as strings, integers, and arrays.

Using Data Types

PHP supports several data types including strings, integers, arrays, and more. Strings are used to store text and are surrounded by single or double quotes. Integers are used to store whole numbers. Arrays are used to store multiple values and can be indexed or associative.

Also Check: Web Development Companies in New Jersey

PHP also supports other data types such as booleans, floats, and objects. Understanding and using different data types is important for creating efficient and accurate scripts.

Control Structures

If/else Statements

If/else statements are used to control the flow of a script based on certain conditions. The basic syntax for an if/else statement is as follows:

if (condition) {
// code to be executed if condition is true
} else {
// code to be executed if condition is false

It’s also possible to chain multiple conditions together using “elseif” like this:

if (condition1) {
    // code to be executed if condition1 is true
} elseif (condition2) {
    // code to be executed if condition1 is false and condition2 is true
} else {
    // code to be executed if condition1 and condition2 are false

For and While Loops

For and while loops are used to repeat a block of code multiple times. The basic syntax for a for loop is as follows:

for ($i = 0; $i < 10; $i++) {
    // code to be executed

While the loop is similar, the condition is checked before the code is executed:

$i = 0;
while ($i < 10) {
    // code to be executed

Switch Statements

Switch statements are used to perform different actions based on different conditions. The basic syntax for a switch statement is as follows:

switch (expression) {
    case value1:
        // code to be executed if expression == value1
    case value2:
        // code to be executed if expression == value2
        // code to be executed if expression is not matched with any value


Functions are used to group a block of code that can be reused multiple times throughout a script. The basic syntax for a function is as follows:

function functionName($parameter1, $parameter2) {
    // code to be executed
    return $result;

A function can be called by using its name followed by the required parameters in parentheses. For example, functionName(parameter1, parameter2)

It is important to note that these are just the basic syntax for these control structures and there are many other ways to use and customize them to suit your needs.

Built-in Functions

Commonly used String Functions

  • strlen(): The strlen function is used to find the length of a string. It returns the number of characters in the string.
$string = "Hello World";
echo strlen($string); // Output: 11
  • strpos(): The strpos function is used to find the position of the first occurrence of a substring in a string. It returns the index of the first occurrence of the substring or false if the substring is not found.
$string = "Hello World";
echo strpos($string, "World"); // Output: 6
  • substr(): The substr function is used to extract a part of a string. It takes three arguments: the string, the starting position, and the length of the substring.
$string = "Hello World";
echo substr($string, 6); // Output: World

Commonly used Array Functions

  • count(): The count function is used to count the number of elements in an array.
$fruits = array("apple", "banana", "orange");
echo count($fruits); // Output: 3
  • sort(): The sort function is used to sort the elements of an array in ascending order.
$numbers = array(3, 1, 2);
print_r($numbers); // Output: Array ( [0] => 1 [1] => 2 [2] => 3 )
  • array_search(): The array_search function is used to search an array for a value and returns the key of the first matching element or false if not found.
$fruits = array("apple", "banana", "orange");
echo array_search("banana", $fruits); // Output: 1

Also Check: Web Development Companies in Chicago

Commonly used Mathematical Functions

  • abs(): The abs function is used to get the absolute value of a number.
$number = -5;
echo abs($number); // Output: 5
  • pow(): The pow function is used to raise a number to a power. It takes two arguments: the base number and the exponent.
$base = 2;
$exponent = 3;
echo pow($base, $exponent); // Output: 8
  • round(): The round function is used to round a number to a specified number of decimal places.
$number = 3.14;
echo round($number, 2); // Output: 3.14

These are just a few examples of the many built-in functions available in PHP. There are many other functions available for specific tasks such as working with dates, files, and databases.

Working with Forms

How to Create A Form in HTML

Creating a form in HTML is relatively simple. The basic structure of a form is an opening <form> tag and a closing </form> tag. Within this structure, you can add various form elements such as text inputs, radio buttons, and submit buttons.

Here is an example of a basic form with text input and a submit button:

<form action="submit.php" method="post">
  <label for="name">Name:</label>
  <input type="text" id="name" name="name">
  <input type="submit" value="Submit">

The action attribute on the <form> tag specifies the file that will handle the form data when the user submits it. The method the attribute specifies the method by which the data will be sent to the server, either “get” or “post”.

In this example, the form data will be sent to a file called “submit.php” using the “post” method.

How to retrieve form data in PHP

Once the form data has been sent to the server, you can retrieve it in PHP using the $_POST or $_GET superglobal arrays, depending on the method you used in the form.

Here’s an example of how to retrieve the data from the form above:

$name = $_POST["name"];

The above code retrieves the value of the “name” input from the form and assigns it to the $name variable.

How to Validate Form Data

Validating form data is an important step in ensuring that the data submitted by the user is accurate and can be safely processed by your application. There are many ways to validate form data in PHP, but a common method is to use built-in functions such as isset() and empty() to check if the data is present and not empty, and is_numeric() or filter_var() to check if the data is of the correct data type.

Here is an example of how to validate a form input for a phone number:

if (isset($_POST["phone"]) && !empty($_POST["phone"]) && is_numeric($_POST["phone"])) {
$phone = $_POST["phone"];
} else {
$errors[] = "Invalid phone number.";

It’s also a good practice to use regular expressions to check if the data matches a specific pattern.

Working with Database

How to Connect to a Database

To connect to a database in PHP, you will need to use the mysqli or PDO extension. Both extensions provide similar functionality but mysqli is generally considered to be the more lightweight and efficient option.

Here is an example of how to connect to a MySQL database using the mysqli extension:

$host = "localhost";
$user = "username";
$password = "password";
$dbname = "databasename";

$conn = mysqli_connect($host, $user, $password, $dbname);

if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());

In the above example, the connection is established using the mysqli_connect() function, which takes four parameters: the hostname, the username, the password, and the database name.

If the connection fails, the script exits and displays an error message.

How to Perform CRUD Operations

Once you have connected to a database, you can perform CRUD (Create, Read, Update, Delete) operations using various SQL commands.

Also Check: How to Secure Your WordPress Website from Hackers

Here are some examples of how to perform these operations using the mysqli extension:

  • Create: To insert a new record into a table, you can use the mysqli_query() function, which takes two parameters: the connection object and the SQL query.
$query = "INSERT INTO users (name, email) VALUES ('John Doe', '')";
$result = mysqli_query($conn, $query);
  • Read: To retrieve data from a table, you can use the mysqli_query() function and then use mysqli_fetch_assoc() to fetch the rows one at a time.
$query = "SELECT * FROM users";
$result = mysqli_query($conn, $query);

while ($row = mysqli_fetch_assoc($result)) {
    echo $row['name'] . " " . $row['email'] . "<br>";
  • Update: To update an existing record in a table, you can use the mysqli_query() function and the SQL UPDATE statement.
$query = "UPDATE users SET email = '' WHERE id = 1";
$result = mysqli_query($conn, $query);
  • Delete: To delete an existing record in a table, you can use the mysqli_query() function and the SQL DELETE statement.
$query = "DELETE FROM users WHERE id = 1";
$result = mysqli_query($conn, $query);

How To Use Prepared Statements To Prevent SQL Injection

Prepared statements are a feature of the mysqli and PDO extensions that allow you to separate the SQL query from the data being inserted into it, thereby preventing any malicious code from being executed.

Here is an example of how to use a prepared statement to insert data into a database using the mysqli extension:

$name = "John Doe";
$email = "";

$stmt = mysqli_prepare($conn, "INSERT INTO users (name, email) VALUES (?, ?)");
mysqli_stmt_bind_param($stmt, "ss", $name, $email);

In the above example, the mysqli_prepare() function is used to create a prepared statement and the mysqli_stmt_bind_param() function is used to bind the values of the $name and $email variables to the placeholders in the query (indicated by the ? characters). The mysqli_stmt_execute() function is then used to execute the prepared statement.

By using prepared statements, any malicious code that may be included in the $name or $email variables will be treated as a simple string, rather than being executed as part of the query.

Tips and Tricks for PHP Cheat Sheet

Debugging PHP Code

  • Employ the error_reporting() function to display errors and warnings.
  • Use the var_dump() function to display the contents of a variable.
  • Use the print_r() function to display the contents of an array.
  • Also, use a debugging tool such as Xdebug to step through your code and inspect variables.

Improving Performance

  • Use caching techniques, such as opcode caching, to speed up the execution of your code.
  • Use a PHP accelerator, such as APC or OpCache, to improve the performance of your code.
  • Employ a Content Delivery Network (CDN) to serve static assets, such as images and stylesheets.
  • Avoid using regular expressions where possible, as they can be slow to execute.

Securing Your PHP Code

  • Use prepared statements and parameterized queries to prevent SQL injection.
  • Use the htmlspecialchars() function to escape any user-supplied data that is displayed on a web page.
  • Employ the password_hash() function to hash passwords.
  • Use the session_regenerate_id() function to regenerate the session ID after a successful login.

By following these tips and tricks, you can improve the performance, security, and maintainability of your PHP code.

Also Check: Advantages of Having Custom Website Developed by Expert Web Development Team


Summary of Key Points

  • PHP is a server-side scripting language used for web development.
  • To write a PHP script, you need to use the <?php tag to open and close the script.
  • You can include PHP code in an HTML file by using the <?php tag to embed the code within the HTML.
  • PHP supports several data types, including strings, integers, arrays, and more.
  • Control structures, such as if/else statements, for and while loops, and switch statements, allow you to control the flow of your code.
  • Built-in functions, such as strlen(), strpos(), sort(), count(), and abs(), provide common functionality for working with data.
  • Forms can be created and processed using HTML and PHP, and form data can be validated to ensure it is correct.
  • PHP provides a variety of functions for working with databases, such as mysqli and PDO extensions, that can be used to connect to a database, perform CRUD operations, and prevent SQL injection.

Additional Resources for Further Learning

This article is all about the PHP cheat sheet and provided an overview of the basics of PHP and some tips on how to write efficient and secure PHP code. It is important to keep learning and experimenting with the language in order to become proficient with it.

It is also important to keep an eye on the latest updates and advancements in the PHP community in order to stay current with best practices and new features.

Sharing is Caring

You May Also Like

More From Author

+ There are no comments

Add yours