PHP Reference & Cheatsheet — Complete Guide
In this tutorial, you'll learn about PHP Reference & Cheatsheet. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.
Learning Path
flowchart LR
A["Php Overview"] --> B["Core Concepts"]
B --> C["Intermediate Topics"]
C --> D["Advanced Topics"]
D --> E["Practical Applications"]
A --> F["You Are Here"]
style F fill:#f90,color:#fff
A comprehensive PHP reference for daily development — syntax, data types, built-in functions, database access, security patterns, and common configurations.
PHP Tags & Syntax
<?php // Standard opening tag (always works)
<?= // Short echo tag — same as <?php echo
// // Single-line comment
# // Also single-line comment
/* */ // Multi-line comment
/** */ // DocBlock comment for documentation
; // Statement terminator (required)
Variables & Superglobals
$var // Variable (must start with $)
$_SERVER // Server & execution environment info
$_GET // URL query parameters
$_POST // HTTP POST data
$_REQUEST // GET + POST + COOKIE combined
$_SESSION // Session variables
$_COOKIE // HTTP cookies
$_FILES // File upload data
$_ENV // Environment variables
$GLOBALS // All global scope variables
Data Types
| Type | Example | Check function |
|---|---|---|
string |
"hello", 'world' |
is_string() |
int |
42, -5 |
is_int() |
float |
3.14 |
is_float() |
bool |
true, false |
is_bool() |
array |
[1, 2], ["key" => "val"] |
is_array() |
object |
new ClassName() |
is_object() |
null |
null |
is_null() |
Control Flow Quick Reference
if (condition) { } else { }
if (condition): else: endif; // Alternative syntax
switch (expr) { case val: break; }
match (expr) { val => result, } // PHP 8+, returns value
for ($i = 0; $i < n; $i++) { }
foreach ($array as $value) { }
foreach ($array as $key => $value) { }
while (condition) { }
do { } while (condition);
break n; // Exit n levels
continue n; // Skip n levels
String Functions
| Function | Description |
|---|---|
strlen($s) |
String length |
strpos($s, $needle) |
Find position (false if not found) |
substr($s, start, length) |
Extract substring |
str_replace($search, $replace, $subject) |
Replace all occurrences |
strtolower($s) / strtoupper($s) |
Case conversion |
trim($s) |
Strip whitespace from both ends |
explode($delim, $s) |
String to array |
implode($glue, $arr) |
Array to string |
htmlspecialchars($s) |
Escape HTML entities (XSS prevention) |
number_format($num, 2) |
Format with comma separators |
Array Functions
| Function | Description |
|---|---|
count($arr) |
Element count |
array_push($arr, ...) / array_pop($arr) |
Stack operations |
in_array($needle, $arr) |
Check if value exists |
array_key_exists($key, $arr) |
Check if key exists |
array_keys($arr) / array_values($arr) |
Get all keys/values |
array_merge($a, $b) |
Merge arrays |
array_map($callback, $arr) |
Transform each element |
array_filter($arr, $callback) |
Filter elements |
array_reduce($arr, $callback, $init) |
Reduce to single value |
array_unique($arr) |
Remove duplicates |
array_reverse($arr) |
Reverse order |
sort($arr) / asort($arr) / ksort($arr) |
Sorting variants |
array_slice($arr, offset, len) |
Extract portion |
PDO Database
// Connect
$pdo = new PDO("mysql:host=$host;dbname=$db;charset=utf8mb4", $user, $pass, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
]);
// Prepared statements (SAFE)
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([$id]);
$row = $stmt->fetch();
$rows = $stmt->fetchAll();
$stmt = $pdo->prepare("INSERT INTO users (name, email) VALUES (:name, :email)");
$stmt->execute(["name" => $name, "email" => $email]);
$id = $pdo->lastInsertId();
// Transactions
$pdo->beginTransaction();
$pdo->commit();
$pdo->rollBack();
Sessions & Cookies
session_start(); // Before any output
$_SESSION["key"] = "value"; // Set session var
unset($_SESSION["key"]); // Remove
session_destroy(); // Destroy all
session_regenerate_id(true); // After login
setcookie("name", "value", time()+86400, "/", "", true, true);
$_COOKIE["name"] ?? null; // Read cookie
Security Best Practices
// Password hashing
$hash = password_hash($password, PASSWORD_BCRYPT, ["cost" => 12]);
password_verify($password, $hash);
password_needs_rehash($hash, PASSWORD_BCRYPT, ["cost" => 12]);
// XSS prevention
htmlspecialchars($userInput, ENT_QUOTES, "UTF-8");
// SQL injection prevention
// Use PDO prepared statements exclusively
// CSRF token
bin2hex(random_bytes(32)); // Generate token
// File upload safety
finfo_file(finfo_open(FILEINFO_MIME_TYPE), $tmpName);
move_uploaded_file($tmpName, $dest);
Common PHP ini Directives
display_errors = On ; Show errors (dev only)
error_reporting = E_ALL ; Report all errors
max_execution_time = 30 ; Max seconds
memory_limit = 128M ; Per-script memory
upload_max_filesize = 2M ; Max upload size
post_max_size = 8M ; Max POST size
date.timezone = UTC ; Default timezone
Common Mistakes Beginners Make
1. Skipping the Fundamentals
Many beginners jump straight to advanced topics without mastering the basics. Take time to understand the core concepts before moving on.
2. Not Practicing Enough
Reading tutorials without writing code leads to shallow understanding. Code along with every example and experiment on your own.
3. Ignoring Error Messages
Error messages tell you exactly what went wrong. Read them carefully — they usually point to the line and type of issue.
4. Copy-Pasting Without Understanding
It's tempting to copy code from tutorials, but typing it yourself and understanding each line builds real skill.
5. Giving Up Too Early
Every developer hits frustrating bugs. Take breaks, ask for help, and remember that struggling is part of learning.
FAQ
What's Next
| Lesson | Description |
|---|---|
| {{< ref "laravel.md" >}} | Modern PHP framework |
| {{< ref "symfony.md" >}} | Enterprise PHP framework |
| {{< ref "../nodejs/reference.md" >}} | Node.js reference |
| MySQL | Database reference |
| Laravel | Framework reference |
What's Next
Congratulations on completing this Php Reference tutorial! Here's where to go from here:
- Practice daily — Consistency is more important than long study sessions
- Build a project — Apply what you learned by building something real
- Explore related topics — Check out other tutorials in the same category
- Join the community — Discuss with other learners and share your progress
Remember: every expert was once a beginner. Keep coding!
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro