PHP
PHP Cheat Sheet
A one-page reference for PHP 8.2 and newer: syntax, types, strings, operators, loops, functions, arrays, forms, files and PDO. Results after → show what PHP returns.
Running PHP Lesson
php -v | Shows the installed PHP version |
php hello.php | Runs a script in the terminal |
php -S localhost:8000 | Built-in development server for the current folder |
<?php phpinfo(); | Page listing your PHP settings; never leave it online |
PHP runs on the server; the browser only receives the HTML it outputs.
Syntax and variables Lesson
<?php … ?> | PHP code lives between these tags |
echo "Hi", " there"; | Prints one or more values |
<?= $name ?> | Short echo tag inside HTML |
// note # note /* … */ | One-line and multi-line comments |
$city = "Chennai"; | Variables start with $; end statements with ; |
$City and $city | Two different variables: names are case-sensitive |
const SITE = "Shop"; | A constant; no $ |
define("MAX_ITEMS", 10); | A constant defined at runtime |
In a file with only PHP, leave out the closing ?> to avoid stray whitespace.
Data types Lesson
int float string bool array null | The main types you will use |
var_dump($x); | Shows the type and value, e.g. int(42) |
gettype(1.5) | → "double" (the historical name for float) |
is_int($x) is_string($x) is_null($x) | Type checks that return true or false |
(int) "42abc" | → 42 (casting) |
intdiv(7, 2) | → 3, while 7 / 2 → 3.5 |
0.1 + 0.2 == 0.3 | → false: floats are not exact |
false 0 0.0 "" "0" [] null | Falsy values; note "0" is falsy |
declare(strict_types=1); | First line: no automatic conversion of scalar arguments |
Strings Lesson
'Hi $name' | Single quotes: printed exactly as written |
"Hi $name" | Double quotes: variables are replaced |
"Total: {$order['total']}" | Braces for array items inside a string |
$a . $b $s .= "!" | Join strings with a dot |
strlen("Chennai") | → 7 (bytes; use mb_strlen() for Tamil text) |
strtoupper("chai") | → "CHAI" |
ucfirst("madurai") | → "Madurai" |
trim(" hi ") | → "hi" |
substr("Pondicherry", 0, 4) | → "Pond" |
str_contains($s, "pay") | true/false; also str_starts_with, str_ends_with |
str_replace("tea", "coffee", "tea time") | → "coffee time" |
number_format(1234567.891, 2) | → "1,234,567.89" |
sprintf("%.2f", 3.14159) → "3.14" formats numbers inside text.
Operators Lesson
10 % 3 2 ** 3 | → 1 (remainder), 8 (power) |
+= -= *= .= | Combined assignment |
"1" == 1 | → true (loose: converts types) |
"1" === 1 | → false (strict: type must match too) |
!= !== | Not equal, loose and strict |
1 <=> 2 | → -1 (spaceship gives -1, 0 or 1) |
&& || ! | And, or, not |
$name ?? "Guest" | Fallback if null or not set |
$x ??= 9; | Assign only if $x is null or not set |
$age >= 18 ? "Adult" : "Minor" | Ternary: short if/else |
$user?->address | Nullsafe: gives null instead of an error |
Prefer === and !==; loose comparison has surprising rules.
Conditions Lesson
if ($marks >= 90) { … } | Runs the block when the condition is true |
elseif ($marks >= 50) { … } else { … } | More tests, then a fallback |
match ($code) { 200 => 'OK', default => '?' } | PHP 8: strict comparison, returns a value |
404, 410 => 'Gone', | One match arm can list several values |
UnhandledMatchError | Thrown if no arm matches and there's no default |
switch ($day) { case 'Sun': …; break; } | Older form: loose comparison, needs break |
isset($x) | True if set and not null |
empty($x) | True if unset or falsy |
<?php if ($ok): ?> … <?php endif; ?> | Alternative syntax for HTML templates |
Loops Lesson
for ($i = 1; $i <= 5; $i++) { … } | Counts with a start, test and step |
while ($n > 0) { … } | Repeats while the condition is true |
do { … } while ($n > 0); | Runs at least once |
foreach ($items as $item) { … } | Each value in an array |
foreach ($prices as $name => $price) | Each key and value |
foreach ($nums as &$n) { $n *= 2; } unset($n); | By reference changes the array; unset afterwards |
break; continue; | Leave the loop / skip to the next round |
break 2; | Leaves two nested loops |
<?php foreach ($rows as $r): ?> … <?php endforeach; ?> | Template form for HTML |
Functions Lesson
function greet(string $name): string { … } | Typed parameter and return type |
function tax(float $amt, float $rate = 0.18) | Default parameter value |
tax(rate: 0.05, amt: 100) | Named arguments (PHP 8), any order |
?string $note | Nullable: a string or null |
int|float $n | Union type: either type is accepted |
function logMessage(string $m): void | Returns nothing |
function sum(int ...$nums) | Variadic: any number of arguments as an array |
static $count = 0; | Keeps its value between calls |
function ($x) use ($rate) { … } | Anonymous function; use brings in outer variables |
fn($x) => $x * $rate | Arrow function: one expression, reads outer variables |
Functions cannot see outside variables; pass them as parameters instead of using global.
Arrays Lesson
$fruits = ["mango", "banana"]; | Indexed array, starting at 0 |
$p = ["name" => "Ravi", "age" => 30]; | Associative array: key => value |
$fruits[] = "guava"; | Adds to the end |
count($fruits) | Number of items |
in_array("mango", $fruits, true) | Strict search; true or false |
array_key_exists("age", $p) | True even if the value is null |
sort() rsort() asort() ksort() | By value; reverse; keep keys; by key |
usort($rows, fn($a, $b) => $a['price'] <=> $b['price']); | Sort with your own rule |
array_map(fn($n) => $n * 2, [1, 2, 3]) | → [2, 4, 6] |
array_filter($nums, fn($n) => $n > 2) | Keeps matching items (and their keys) |
implode(", ", $fruits) explode(",", $csv) | Array to string / string to array |
[$a, $b] = [1, 2]; | Destructuring into variables |
Forms: GET and POST Lesson
$_GET['q'] ?? '' | Value from the URL query string |
$_POST['email'] ?? '' | Value from a POST form body |
$_SERVER['REQUEST_METHOD'] === 'POST' | Was the form submitted? |
trim($_POST['name'] ?? '') | Remove spaces before checking |
filter_var($email, FILTER_VALIDATE_EMAIL) | The email if valid, otherwise false |
filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT) | An int, false if invalid, null if missing |
htmlspecialchars($s, ENT_QUOTES, 'UTF-8') | Escape user text before printing it |
header('Location: thanks.php'); exit; | Redirect after a successful POST |
session_start(); | Call before any output to use $_SESSION |
bin2hex(random_bytes(32)) | A random CSRF token to store in the session |
hash_equals($_SESSION['token'], $sent) | Timing-safe token comparison |
Validate on the server every time; browser checks are easy to bypass.
Include and files Lesson
include 'header.php'; | Missing file: warning, script continues |
require 'config.php'; | Missing file: fatal error, script stops |
require_once __DIR__ . '/db.php'; | Loads once, path relative to this file |
file_get_contents('notes.txt') | Whole file as a string |
file_put_contents('log.txt', $line, FILE_APPEND); | Writes; the flag adds instead of replacing |
file('list.txt', FILE_IGNORE_NEW_LINES) | Lines as an array |
file_exists('data.json') | true or false |
json_encode($data, JSON_PRETTY_PRINT) | PHP array to JSON text |
json_decode($json, true) | JSON text to an associative array |
$fh = fopen('big.txt', 'r'); fgets($fh); fclose($fh); | Read a large file line by line |
MySQL with PDO Lesson
'mysql:host=localhost;dbname=shop;charset=utf8mb4' | The DSN: driver, host, database, character set |
$pdo = new PDO($dsn, $user, $pass, $options); | Connect to the database |
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION | Errors throw exceptions (the default since PHP 8) |
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC | Rows come back as associative arrays |
$stmt = $pdo->prepare('SELECT * FROM users WHERE id = ?'); | Prepared statement with a placeholder |
$stmt->execute([$id]); | Sends the value separately from the SQL |
'… WHERE email = :email' | Named placeholder: execute(['email' => $email]) |
$stmt->fetch() | Next row, or false when there are none |
$stmt->fetchAll() | All rows as an array |
$pdo->lastInsertId() | ID of the row just inserted |
$stmt->rowCount() | Rows changed by UPDATE or DELETE |
catch (PDOException $e) | Handle database errors; don't show details to visitors |
Never put user input straight into SQL; always use placeholders.