dev.rean.me
php

PHP Cheat Sheet with Example Code

Learn essential PHP syntax, variables, arrays, functions, control structures, MySQL CRUD, REST APIs, and security best practices in simple broken English.

2026-09-24 ยท 8 min read

Share:

Hello my friend! Today I show you complete PHP Cheat Sheet with clear code examples and practical tips! PHP is powerful server-side language for web development and backend APIs. This cheat sheet cover all essential PHP syntax you need every day! Very easy to read and quick to review. Let's get started!

1. Basic PHP Syntax

PHP scripts start with <?php tag. You can mix PHP inside HTML file!

<?php
// Always open PHP script tag
echo "Hello World from PHP!";
?>

๐Ÿ’ก Tip: If your PHP file contains ONLY PHP code (no HTML), it is best practice to omit closing ?> tag at end of file to prevent whitespace bugs!

2. Variables ($variable)

In PHP, all variables must start with $ dollar sign signifier.

$name = "Rean";   // String
$age = 25;       // Integer
$price = 19.99;  // Float
$isOnline = true; // Boolean

๐Ÿ’ก Tip: Variable names in PHP are case-sensitive! $name and $Name are two completely different variables!

3. Data Types

PHP automatically assigns data type based on variable value.

$str = "Hello";        // String
$int = 100;            // Integer
$float = 10.5;         // Float (floating point number)
$bool = true;          // Boolean (true/false)
$arr = [1, 2, 3];      // Array
$obj = new stdClass(); // Object
$empty = null;         // NULL (no value)

๐Ÿ’ก Tip: PHP is dynamically typed language, so you don't need to specify type when creating variables!

4. Output Functions (echo, print_r, var_dump)

Display output on browser screen or debug variables.

$name = "Rean";
$colors = ["Red", "Green", "Blue"];

// echo: Fast output for strings/HTML
echo "Welcome " . $name;

// print_r: Print human-readable array structure
print_r($colors);

// var_dump: Detailed debug info (data type + value + length)
var_dump($colors);

๐Ÿ’ก Tip: Use echo for web page rendering, and var_dump() when debugging complex arrays or objects!

5. Conditional Statements (if...else)

Execute different code blocks based on condition evaluation.

$age = 18;

if ($age >= 18) {
    echo "Adult user";
} else if ($age >= 13) {
    echo "Teenager user";
} else {
    echo "Minor user";
}

๐Ÿ’ก Tip: Always use strict comparison === inside if statements to compare both value and data type!

6. Ternary Operator (Short if...else)

Quick 1-line syntax for simple conditional logic.

$age = 20;

// Short syntax: condition ? valueIfTrue : valueIfFalse
$status = ($age >= 18) ? "Adult" : "Minor";
echo $status; // "Adult"

๐Ÿ’ก Tip: Use ternary operator for short variable assignments or inline HTML attributes, but keep it clean!

7. Loops (for, foreach, while)

Repeat code execution or iterate over arrays easily.

// 1. Standard for loop
for ($i = 0; $i < 5; $i++) {
    echo "Count: " . $i . "<br>";
}

// 2. foreach loop (best for arrays!)
$users = ["John", "Jane", "David"];
foreach ($users as $user) {
    echo "User: " . $user . "<br>";
}

// 3. while loop
$x = 1;
while ($x <= 3) {
    echo "Number: " . $x;
    $x++;
}

๐Ÿ’ก Tip: foreach is fastest and cleanest way to loop through arrays in PHP without manually counting index!

8. Functions & Parameters

Encapsulate reusable logic inside functions.

// Function definition
function calculateTotal($price, $tax = 0.1) {
    $total = $price + ($price * $tax);
    return $total;
}

// Call function
echo calculateTotal(100); // Returns 110

๐Ÿ’ก Tip: You can specify default parameter values (like $tax = 0.1) so caller can omit argument if optional!

9. Indexed Arrays & Functions

Arrays store multiple items inside single variable.

$users = ["John", "Jane"];

// Append new item to end of array
$users[] = "David";

// Count total elements inside array
echo count($users); // 3

// Check if item exists inside array (returns true/false)
if (in_array("John", $users)) {
    echo "John found!";
}

๐Ÿ’ก Tip: Always use in_array($searchItem, $array) to check existence before attempting array manipulation!

10. Associative Arrays (Key-Value Pairs)

Store data with custom key names instead of numeric index numbers.

$user = [
    "name" => "Rean",
    "age" => 25,
    "role" => "Developer"
];

// Access value by key name
echo $user["name"]; // "Rean"

// Loop associative array with key and value
foreach ($user as $key => $value) {
    echo $key . ": " . $value . "<br>";
}

๐Ÿ’ก Tip: Associative arrays are super common in PHP when working with database rows or JSON responses!

11. String Helper Functions

Manipulate and transform string text easily.

$text = "Hello Rean";

echo strlen($text);                     // Get string length
echo strtoupper($text);                 // Convert to UPPERCASE
echo strtolower($text);                 // Convert to lowercase
echo str_replace("Rean", "Dara", $text); // Replace text -> "Hello Dara"

๐Ÿ’ก Tip: String concatenation in PHP uses dot . operator (e.g. $greeting . " " . $name), NOT plus + operator!

12. File Inclusion (include vs require)

Reuse HTML layout headers, footers, or configuration files.

// include: Warns if file missing, but script continues executing
include "header.php";

// require: Stops script execution immediately with fatal error if file missing!
require "config.php";

// require_once: Ensures file is included ONLY once
require_once "database.php";

๐Ÿ’ก Tip: Always use require or require_once for database config and security files so app won't run with missing dependencies!

13. Superglobals & Form Data ($_POST, $_GET)

Receive data sent from HTML forms or URL query parameters.

// Read query parameter from URL (e.g. index.php?id=5)
$id = $_GET["id"] ?? null;

// Read form payload submitted via POST method
$username = $_POST["username"] ?? "";

// Sanitize user input to prevent XSS attacks!
$cleanInput = htmlspecialchars($username);

๐Ÿ’ก Tip: Never trust raw $_POST or $_GET data! Always sanitize input using htmlspecialchars() before displaying on page!

14. Session Management (session_start)

Store persistent user data across multiple page reloads (like login auth).

// Must call session_start() at very top of PHP file!
session_start();

// Set session variable
$_SESSION["user_id"] = 123;
$_SESSION["user_name"] = "Rean";

// Access session variable
echo "Welcome " . $_SESSION["user_name"];

// Destroy session (Logout)
session_destroy();

๐Ÿ’ก Tip: Always call session_start() before sending any HTML output to browser, otherwise header warning occurs!

15. Working with JSON Data (json_encode, json_decode)

Convert data between PHP arrays and JSON strings for REST APIs.

$user = ["name" => "Rean", "age" => 25];

// Convert PHP array to JSON string
$jsonString = json_encode($user); // '{"name":"Rean","age":25}'

// Convert JSON string back to PHP associative array (set 2nd param to true!)
$arrayData = json_decode($jsonString, true);

๐Ÿ’ก Tip: Always pass true as second argument in json_decode($json, true) to get array instead of PHP object!

16. MySQL Database Connection with PDO & Prepared Statements

Securely connect to MySQL database and run SQL queries using PDO.

// Database connection setup
$host = "localhost";
$db   = "test_db";
$user = "root";
$pass = "";

try {
    $pdo = new PDO("mysql:host=$host;dbname=$db;charset=utf8mb4", $user, $pass);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // Prepared Statement (Prevents SQL Injection attack!)
    $stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
    $stmt->execute([$id]);
    $users = $stmt->fetchAll(PDO::FETCH_ASSOC);

} catch (PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}

๐Ÿ’ก Tip: Never concatenate raw variables into SQL query strings (e.g. "SELECT * FROM users WHERE id = " . $id)! Always use Prepared Statements with placeholders ? to stop SQL Injection!

17. Useful Operators Summary

Quick reference for PHP comparison, logical, and string operators:

==    Equal value (loose comparison)
===   Identical (value AND data type)
!=    Not equal
!==   Not identical
&&    Logical AND
||    Logical OR
??    Null Coalescing operator (fallback if null)
.     String Concatenation operator

๐Ÿ’ก Tip: Use Null Coalescing ?? for default fallback value (e.g. $name = $_GET["name"] ?? "Guest";)!

18. Security & Password Hashing

Essential PHP security functions for production web applications.

// 1. Prevent XSS (Cross-Site Scripting) when rendering output
echo htmlspecialchars($userInput, ENT_QUOTES, 'UTF-8');

// 2. Hash user password securely before storing in database
$hashedPassword = password_hash($rawPassword, PASSWORD_DEFAULT);

// 3. Verify password during login
if (password_verify($inputPassword, $hashedPassword)) {
    echo "Password correct! Access granted.";
} else {
    echo "Invalid password!";
}

๐Ÿ’ก Tip: Never use md5() or sha1() for password hashing! Always use password_hash() which uses strong BCRYPT hashing automatically!

Hope this PHP Cheat Sheet help you quickly build backend web applications and database APIs! Bookmark this guide and practice daily. Happy learning my friends! Sharing is caring!

โ† Back to php
Share: