Skip to main content
Quick Reference

PHP Programming Cheatsheet

PHP 8 on one page — tags and CLI, types, operators, control flow, strings, arrays, functions, OOP, exceptions, Composer, forms and sessions, files and JSON, PDO, and interview traps. Built for revision and for looking things up while you code.

14 sections 13 tables 30 code snippets

Tags, Output & Running PHP

Minimal script

<?php
declare(strict_types=1);

echo "Hello, PHP!\n";

function main(): void {
    $name = "Ravi";
    echo "Hello, $name!\n";
}

main();

Run, built-in server, Composer

php hello.php                 # run a script
php -v                         # version
php -l hello.php               # lint only
php -S localhost:8000          # dev server
php -r "echo 2 + 2;"           # one-liner
composer require vlucas/phpdotenv
composer dump-autoload

echo, print, and HTML

<?php
$name = "Ada";
echo "Hi ", $name, "\n";
print "one value only\n";
printf("Score: %03d\n", 7);

# Short echo tag is always available in PHP 8
# <?= htmlspecialchars($name) ?>

Magic constants

NameMeaning
__DIR__Directory of the current file
__FILE__Full path of the current file
__LINE__Current line number
__FUNCTION__Current function name
__CLASS__ / __METHOD__Class / Class::method
__NAMESPACE__Current namespace

Put declare(strict_types=1); as the first statement in every file. It makes scalar type hints reject silent casts such as int parameters receiving "42".

Types, Variables & Casting

Scalars and compounds

<?php
declare(strict_types=1);

$n = 42;            // int
$price = 19.5;      // float
$ok = true;         // bool
$name = "Ada";      // string
$items = [1, 2, 3]; // array
$bag = null;        // null

var_dump($n, $price, $ok, $name);

Checks and casts

<?php
is_int($n);
is_string($name);
is_array($items);
is_null($bag);

$age = (int) "21";
$flag = (bool) 1;
$text = (string) 42;
$copy = (array) $user;

Scalar types

TypeExampleNotes
int42Platform size; no separate long
float3.14IEEE float — avoid for money
string"hi" / 'hi'Binary-safe byte strings
booltrue / falseOnly these two values
array[1, "a" => 2]Ordered map, not a fixed list
objectnew User()Class instance
nullnullUnset or missing value

Variables always start with $. Names are case-sensitive. Function names are not. Prefer snake or the project’s style and stay consistent.

Operators & Comparisons

Everyday operators

<?php
$sum = 2 + 3;
$mod = 7 % 3;
$label = $name ?? "guest";
$name ??= "guest";          // assign only if null
$order = $a <=> $b;         // -1, 0, 1
$city = $user?->address?->city;
$ok = $age >= 18 && $age < 60;

Compare on purpose

<?php
0 == "0";     // true  (loose)
0 === "0";    // false (strict)
0 == "foo";   // false in PHP 8
null ?? "x";  // "x"
false ?? "x"; // false  (?? only replaces null)
isset($a) ? $a : "x";

Operator cheat

OpMeaning
=== / !==Same type and value — default choice
== / !=Loose compare after juggling
??Left side when it is not null
?->Call or read only if the object is not null
<=>Spaceship: -1, 0, or 1
&& || !Boolean logic (and/or bind looser)
. String concatenation
=>Array key/value, match arm, arrow fn

Control Flow

if / elseif / else

<?php
if ($score >= 90) {
    $grade = "A";
} elseif ($score >= 80) {
    $grade = "B";
} else {
    $grade = "C";
}

match (PHP 8)

<?php
$label = match ($status) {
    200, 201 => "ok",
    404 => "missing",
    500 => "server",
    default => "other",
};

Loops

<?php
for ($i = 0; $i < 3; $i++) {
    echo $i;
}

foreach ($users as $id => $user) {
    echo $user["name"];
}

while ($line = fgets($handle)) {
    echo $line;
}

switch vs match

switchmatch
CompareLoose ==Strict ===
Fall-throughYes, needs breakNo — one arm returns
ResultStatementsAn expression
No matchDoes nothingThrows UnhandledMatchError without default

Strings

Quotes and interpolation

<?php
$name = "Ravi";
echo "Hello, $name";
echo 'Hello, $name';          // literal $name
echo "Line\nNext";
$path = __DIR__ . "/data.json";
$html = htmlspecialchars($name, ENT_QUOTES, "UTF-8");

Common string functions

<?php
strlen("hi");
str_contains($hay, "php");     // PHP 8
str_starts_with($url, "https");
str_ends_with($file, ".php");
trim("  hi  ");
strtolower("PHP");
str_replace("php", "PHP", $s);
$parts = explode(",", "a,b,c");
$line = implode("-", ["a", "b"]);
sprintf("id=%04d", 7);

Bytes vs characters

FunctionUse
strlen / substrBytes. Fine for ASCII ids and paths
mb_strlen / mb_substrCharacters. Use for user-facing Unicode
preg_matchRegex. Add the u modifier for UTF-8
htmlspecialcharsEscape text before putting it in HTML

Arrays

Lists and maps

<?php
$nums = [10, 20, 30];
$nums[] = 40;

$user = [
    "name" => "Ravi",
    "age" => 21,
];
$user["city"] = "Hyderabad";

echo $user["name"];
echo $nums[0];

Transform

<?php
$doubled = array_map(fn($n) => $n * 2, $nums);
$adults = array_filter($users, fn($u) => $u["age"] >= 18);
$sum = array_reduce($nums, fn($carry, $n) => $carry + $n, 0);

$names = array_column($users, "name");
usort($users, fn($a, $b) => $a["age"] <=> $b["age"]);

Lookups

CallQuestion it answers
isset($a[$k])Key exists and value is not null
array_key_exists($k, $a)Key exists, even if value is null
in_array($v, $a, true)Value exists. Pass true for strict
count($a)Number of elements
array_merge($a, $b)New array. Numeric keys are renumbered
$a + $bUnion. Keys in $a win

Functions

Typed function

<?php
function greet(string $name, string $title = "Hi"): string {
    return $title . ", " . $name;
}

echo greet("Ravi");
echo greet(name: "Ravi", title: "Hello");

Arrow, variadic, closure

<?php
$add = fn(int $a, int $b): int => $a + $b;

function total(int ...$nums): int {
    return array_sum($nums);
}

$prefix = "id";
$make = function (int $n) use ($prefix): string {
    return $prefix . "-" . $n;
};

Arguments

FormMeaning
string $name = "Ada"Typed optional parameter
?string $bioString or null
int|string $idUnion type (PHP 8)
int ...$numsVariadic — arrives as a list
name: "Ravi"Named argument (PHP 8)
fn($x) => $x + 1Arrow function. Captures outer vars by value

Classes, Traits & Enums

Constructor promotion

<?php
class User {
    public function __construct(
        public readonly string $name,
        private int $age,
    ) {}

    public function greet(): string {
        return "Hi, " . $this->name;
    }
}

$u = new User("Ravi", 21);

Interface, trait, enum

<?php
interface Greeter {
    public function greet(): string;
}

trait Timestamps {
    public ?string $createdAt = null;
}

enum Status: string {
    case Draft = "draft";
    case Live = "live";
}

Visibility and reuse

KeywordUse
public / protected / privateWho can read or call the member
readonlySet once, then immutable (PHP 8.1)
extendsOne parent class
implementsOne or more interfaces
traitReuse methods without inheritance
enumA closed set of cases (PHP 8.1)

Exceptions & Errors

try / catch / finally

<?php
try {
    if ($age < 0) {
        throw new InvalidArgumentException("age must be >= 0");
    }
} catch (InvalidArgumentException $e) {
    error_log($e->getMessage());
} finally {
    // close handles here
}

Custom exception

<?php
class NotFound extends RuntimeException {}

function findUser(int $id): User {
    $user = $repo->find($id);
    if ($user === null) {
        throw new NotFound("user $id");
    }
    return $user;
}

What to catch

TypeWhen
InvalidArgumentExceptionBad input the caller can fix
RuntimeExceptionFailure that depends on the environment
LogicExceptionA bug in the program
ErrorEngine errors. Catch only at the edge
ThrowableBoth Exception and Error

Namespaces, Includes & Composer

Namespace and use

<?php
namespace App\Models;

use App\Support\Str;
use PDO;

class Post {
    public function slug(): string {
        return Str::slug($this->title);
    }
}

Include vs autoload

# composer.json
{
  "autoload": {
    "psr-4": { "App\\": "src/" }
  }
}

# then:
composer dump-autoload
# require __DIR__ . "/vendor/autoload.php";

Loading code

FormIf the file is missing
includeWarning, script continues
requireFatal error
include_once / require_onceSkip if already loaded
Composer PSR-4Class name maps to a file path

Forms, Sessions & Cookies

Read a form safely

<?php
declare(strict_types=1);

$name = trim((string) ($_POST["name"] ?? ""));
$email = filter_input(INPUT_POST, "email", FILTER_VALIDATE_EMAIL);

if ($name === "" || $email === false) {
    http_response_code(422);
    exit("Invalid form");
}

Session and cookie

<?php
session_start();
$_SESSION["user_id"] = 15;

setcookie("theme", "dark", [
    "expires" => time() + 60 * 60 * 24 * 30,
    "path" => "/",
    "httponly" => true,
    "samesite" => "Lax",
    "secure" => true,
]);

Superglobals

ArrayHolds
$_GETQuery-string parameters
$_POSTForm body (application/x-www-form-urlencoded or multipart)
$_REQUESTGet, post, and cookie mixed — avoid
$_SESSIONData stored on the server for this browser
$_COOKIECookies the browser sent
$_FILESUploaded files
$_SERVERRequest method, URI, headers, server paths

Escape with htmlspecialchars on the way out to HTML. Validate on the way in. Never build SQL by concatenating $_POST values.

Files & JSON

Read and write

<?php
$text = file_get_contents(__DIR__ . "/notes.txt");
file_put_contents(__DIR__ . "/out.txt", $text . "\n", FILE_APPEND);

$fh = fopen(__DIR__ . "/log.txt", "a");
if ($fh === false) {
    throw new RuntimeException("cannot open log");
}
fwrite($fh, "ok\n");
fclose($fh);

JSON

<?php
$json = json_encode(["ok" => true], JSON_THROW_ON_ERROR);
$data = json_decode($json, true, 512, JSON_THROW_ON_ERROR);

if (!is_array($data) || !isset($data["ok"])) {
    throw new RuntimeException("unexpected JSON");
}

json_decode($json, true) returns associative arrays. Without true you get stdClass objects. JSON_THROW_ON_ERROR turns bad JSON into an exception instead of null.

PDO & MySQL

Connect and query

<?php
$pdo = new PDO(
    "mysql:host=localhost;dbname=app;charset=utf8mb4",
    $user,
    $pass,
    [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    ],
);

$stmt = $pdo->prepare("SELECT id, name FROM users WHERE id = ?");
$stmt->execute([$id]);
$row = $stmt->fetch();

Insert with named placeholders

<?php
$stmt = $pdo->prepare(
    "INSERT INTO users (name, email) VALUES (:name, :email)"
);
$stmt->execute([
    "name" => $name,
    "email" => $email,
]);
$newId = (int) $pdo->lastInsertId();

Rules

DoWhy
Prepared statementsParameters are data, not SQL
ERRMODE_EXCEPTIONFailures throw instead of returning false
utf8mb4Full Unicode, including emoji
TransactionsbeginTransaction / commit / rollBack for multi-step writes

Interview Traps

Traps worth memorising

TrapWhat happensPrefer
== instead of ===Type juggling ("0" == false)Strict compare
empty("0")True — string zero looks empty=== "" or === null
switch on mixed typesLoose compare, surprising armsmatch
foreach with &$item$item stays a reference after the loopunset($item) after the loop
Float money0.1 + 0.2 is not 0.3Store paise/cents as int
String-built SQLSQL injectionPDO placeholders
Echo then header()Headers already sentSend headers before any output
include for required codeMissing file becomes a warningrequire or Composer
strlen on Hindi/emojiCounts bytes, not charactersmb_strlen
$_REQUESTMixes get, post, and cookiesRead one superglobal
Error display in productionLeaks paths and SQLdisplay_errors=Off, log instead
@ error suppressorHides the failureCheck the return value or catch

Reference leftover

<?php
$nums = [1, 2, 3];
foreach ($nums as &$n) {
    $n *= 2;
}
unset($n); // drop the reference

foreach ($nums as $n) {
    echo $n; // 2 4 6
}

Loose empty check

<?php
empty("0");          // true
empty(0);            // true
empty("00");         // false

$value = "0";
$missing = ($value === "" || $value === null);

How to use this page: skim the jump chips, drill the tables, then type every snippet in php -a or a small file. Pair forms and PDO with a real request so the superglobals are not abstract.