PHP
PHP 8.2+
Table of Contents
- Variables & Constants
- Data Types
- Operators
- String Operations
- Array Operations
- Control Flow
- Functions
- Classes & OOP
- Exception Handling
- File Operations
- Forms & Input Handling
- Common Built-in Functions
1. Variables & Constants
// Variables ($ prefix required)
$name = "Alice";
$age = 30;
$price = 9.99;
// Constants (cannot be changed)
define("MAX_SIZE", 100);
const APP_NAME = "MyApp";Variable Scope
$globalVar = "global";
function example() {
// Accessing a global variable inside a function requires the global keyword
global $globalVar;
echo $globalVar; // "global"
}2. Data Types
Type Overview
| Type | Example | Description |
|---|---|---|
string | "hello", 'world' | String |
int | 42, -10 | Integer |
float | 3.14 | Floating point number |
bool | true, false | Boolean |
array | [1, 2, 3] | Array |
null | null | No value |
Type Checking / Existence
is_string($val); // check if string
is_int($val); // check if integer
is_array($val); // check if array
is_numeric($val); // check if numeric value ("42" returns true)
isset($val); // check if variable is defined and not null
empty($val); // check if empty (0, "", [], null, false)Type Conversion / Casting
(int)"42px"; // 42
(float)"3.14"; // 3.14
(string)42; // "42"
(bool)0; // false
(bool)"0"; // false ← note: "0" is falsy
intval("42px"); // 423. Operators
Comparison Operators
// == performs type coercion (behavior differs by PHP version)
0 == "foo"; // PHP 7.x: true (non-numeric string cast to 0) — PHP 8.0+: false
// === compares value AND type (recommended)
1 === 1; // true
1 === "1"; // false
// Spaceship operator (useful in sort comparators)
1 <=> 2; // -1 (left is smaller)
2 <=> 2; // 0 (equal)
3 <=> 2; // 1 (left is larger)Null Coalescing Operator
$name = $_GET["name"] ?? "Guest"; // "Guest" if null or undefined
$val = $a ?? $b ?? "default"; // chainable
// Null coalescing assignment
$config["debug"] ??= false; // assign false if not defined4. String Operations
$str = "Hello, World!";
// Length
strlen($str); // 13
mb_strlen("hello"); // multibyte-safe length
// Search (PHP 8.0+)
str_contains($str, "World"); // true
str_starts_with($str, "Hello"); // true
str_ends_with($str, "!"); // true
strpos($str, "World"); // 7 (returns false if not found)
// Transform
strtoupper($str); // "HELLO, WORLD!"
strtolower($str); // "hello, world!"
str_replace("World", "PHP", $str); // "Hello, PHP!"
trim(" hello "); // "hello"
// Split / join
explode(",", "a,b,c"); // ["a", "b", "c"]
implode("-", ["a", "b", "c"]); // "a-b-c"
// Extract
substr($str, 7, 5); // "World"
mb_substr("hello", 1, 3); // multibyte-safe substringHeredoc
$name = "Alice";
$text = <<<EOT
Hello, {$name}.
This is a multi-line string.
EOT;String Formatting
$msg = sprintf("Name: %s, Age: %d", "Alice", 30);
// "Name: Alice, Age: 30"
sprintf("%.2f", 3.14159); // "3.14"
sprintf("%05d", 42); // "00042"
number_format(1234567.89, 2, ".", ","); // "1,234,567.89"5. Array Operations
Array Types
// Indexed array
$fruits = ["apple", "banana", "cherry"];
$fruits[0]; // "apple"
$fruits[] = "grape"; // append to end
// Associative array
$user = [
"name" => "Alice",
"age" => 30,
"role" => "admin",
];
$user["name"]; // "Alice"
// Multi-dimensional array
$matrix = [[1, 2], [3, 4]];
$matrix[0][1]; // 2Basic Operations
$arr = [1, 2, 3];
count($arr); // 3 (element count)
$last = array_pop($arr); // remove and return last element
$first = array_shift($arr);// remove and return first element
// Search
in_array(2, $arr); // true
array_search(2, $arr); // returns index (false if not found)
array_key_exists("name", $user); // check if key exists in associative arrayTransform / Manipulate
$numbers = [3, 1, 4, 1, 5, 9];
// map / filter / reduce
$doubled = array_map(fn($n) => $n * 2, $numbers);
$evens = array_filter($numbers, fn($n) => $n % 2 === 0);
$sum = array_reduce($numbers, fn($carry, $n) => $carry + $n, 0);
// Sort (mutates original array)
sort($numbers); // ascending
rsort($numbers); // descending
usort($numbers, fn($a, $b) => $a <=> $b); // custom sort
// Slice / merge / deduplicate
array_slice($numbers, 1, 3); // 3 elements starting at index 1
array_merge([1, 2], [3, 4]); // [1, 2, 3, 4]
array_unique([1, 2, 2, 3]); // [1, 2, 3]
array_reverse($numbers); // reverse order
// Get keys / values
array_keys($user); // ["name", "age", "role"]
array_values($user); // ["Alice", 30, "admin"]6. Control Flow
if / elseif / else
$score = 75;
if ($score >= 90) {
echo "A";
} elseif ($score >= 70) {
echo "B";
} else {
echo "C";
}
// Ternary operator
$label = $score >= 70 ? "Pass" : "Fail";
// match expression (PHP 8.0+)
$grade = match (true) {
$score >= 90 => "A",
$score >= 70 => "B",
default => "C",
};switch / match
$status = "loading";
// match (strict comparison — PHP 8.0+)
$message = match ($status) {
"loading" => "Loading",
"success" => "Success",
"error" => "Error",
default => "Unknown",
};
// switch (loose comparison)
switch ($status) {
case "loading":
echo "Loading";
break;
default:
echo "Unknown";
}Loops
// for
for ($i = 0; $i < 3; $i++) {
echo $i; // 0, 1, 2
}
// foreach (iterate array)
foreach (["a", "b", "c"] as $value) {
echo $value;
}
// foreach (associative array)
foreach ($user as $key => $value) {
echo "{$key}: {$value}";
}
// while
$count = 0;
while ($count < 3) {
$count++;
}
// break / continue
foreach ([1, 2, 3, 4, 5] as $n) {
if ($n === 3) continue;
if ($n === 5) break;
echo $n; // 1, 2, 4
}7. Functions
Basic Syntax & Type Declarations
function add(int $a, int $b): int {
return $a + $b;
}
// Default argument
function greet(string $name = "Guest"): string {
return "Hello, {$name}";
}
// Nullable type (accepts null)
function findUser(?int $id): ?array {
if ($id === null) return null;
return ["id" => $id, "name" => "Alice"];
}
// Union type (PHP 8.0+)
function format(int|float $value): string {
return (string)$value;
}
// No return value
function logMessage(string $msg): void {
echo $msg;
}
// Variadic arguments
function sum(int ...$numbers): int {
return array_sum($numbers);
}
sum(1, 2, 3, 4); // 10Arrow Functions & Anonymous Functions
// Anonymous function (closure) — capture outer variables with use
$multiplier = 3;
$triple = function (int $n) use ($multiplier): int {
return $n * $multiplier;
};
// Arrow function (PHP 7.4+) — captures outer variables automatically
$triple = fn(int $n) => $n * $multiplier;
$triple(5); // 15
// Pass as callback
$squared = array_map(fn($n) => $n ** 2, [1, 2, 3]);8. Classes & OOP
Basic Syntax
class User {
public string $name;
protected int $age;
private string $password;
public function __construct(string $name, int $age, string $password) {
$this->name = $name;
$this->age = $age;
$this->password = $password;
}
public function greet(): string {
return "Hello, {$this->name}";
}
public function getAge(): int {
return $this->age;
}
public static function create(string $name, int $age): static {
return new static($name, $age, "");
}
}
$user = new User("Alice", 30, "secret");
$user->greet(); // "Hello, Alice"
User::create("Bob", 25); // create via static methodConstructor Promotion (PHP 8.0+)
class Product {
public function __construct(
public readonly string $name,
public float $price,
private int $stock = 0,
) {}
public function isAvailable(): bool {
return $this->stock > 0;
}
}
$product = new Product("Apple", 1.50, 10);
$product->name; // "Apple"
$product->isAvailable(); // trueInheritance / Interfaces / Abstract Classes
// Interface
interface Greetable {
public function greet(): string;
}
// Abstract class
abstract class Animal {
abstract public function speak(): string;
public function describe(): string {
return "I am an animal: " . $this->speak();
}
}
// Extend and implement
class Dog extends Animal implements Greetable {
public function __construct(private string $name) {}
public function speak(): string {
return "Woof!";
}
public function greet(): string {
return "Hi, I'm {$this->name}";
}
}
$dog = new Dog("Rex");
$dog instanceof Animal; // true
$dog instanceof Greetable; // trueTraits
trait Timestampable {
private ?DateTime $createdAt = null;
public function setCreatedAt(): void {
$this->createdAt = new DateTime();
}
public function getCreatedAt(): ?DateTime {
return $this->createdAt;
}
}
class Post {
use Timestampable;
public function __construct(public string $title) {}
}9. Exception Handling
try {
throw new RuntimeException("An error occurred");
} catch (RuntimeException $e) {
echo "Error: " . $e->getMessage();
} catch (Exception $e) {
echo "Unexpected error: " . $e->getMessage();
} finally {
echo "Always runs";
}Custom Exceptions
class ValidationException extends RuntimeException {
public function __construct(
string $message,
private readonly string $field,
int $code = 0,
) {
parent::__construct($message, $code);
}
public function getField(): string {
return $this->field;
}
}
try {
throw new ValidationException("Invalid age", "age");
} catch (ValidationException $e) {
echo "[{$e->getField()}] {$e->getMessage()}";
// "[age] Invalid age"
}10. File Operations
// Read
$content = file_get_contents("file.txt");
$lines = file("file.txt", FILE_IGNORE_NEW_LINES); // array of lines
// Write
file_put_contents("file.txt", "Hello, PHP!");
file_put_contents("log.txt", "appended content\n", FILE_APPEND);
// File operations
file_exists("file.txt"); // check existence
unlink("file.txt"); // delete
rename("old.txt", "new.txt"); // rename / move
copy("src.txt", "dst.txt"); // copy
mkdir("new_dir", 0755, true); // create directory (recursive)
// Path operations
basename("/path/to/file.txt"); // "file.txt"
dirname("/path/to/file.txt"); // "/path/to"11. Forms & Input Handling
Superglobal Variables
// GET parameter
$name = $_GET["name"] ?? "";
// POST data
$email = $_POST["email"] ?? "";
// Session
session_start();
$_SESSION["user_id"] = 1;
$userId = $_SESSION["user_id"] ?? null;
unset($_SESSION["user_id"]); // delete key
session_destroy(); // destroy session
// Cookie
setcookie("token", "abc123", time() + 3600, "/");
$token = $_COOKIE["token"] ?? "";Sanitization & Validation
// Validation
filter_var($email, FILTER_VALIDATE_EMAIL); // validate email format
filter_var($url, FILTER_VALIDATE_URL); // validate URL format
filter_var($num, FILTER_VALIDATE_INT); // validate integer
// XSS protection (when outputting to HTML)
echo htmlspecialchars($userInput, ENT_QUOTES, "UTF-8");12. Common Built-in Functions
Numbers
abs(-5); // 5 (absolute value)
ceil(4.1); // 5 (round up)
floor(4.9); // 4 (round down)
round(4.5); // 5 (round to nearest)
round(3.14159, 2); // 3.14 (round to 2 decimal places)
max(1, 2, 3); // 3
min(1, 2, 3); // 1
rand(1, 10); // random integer between 1 and 10Date & Time
// DateTime class (recommended)
$now = new DateTime();
$now->format("Y-m-d H:i:s"); // "2026-03-28 12:00:00"
$date = new DateTime("2026-01-01");
$date->modify("+1 month");
$date->format("Y-m-d"); // "2026-02-01"
// Date difference
$d1 = new DateTime("2026-01-01");
$d2 = new DateTime("2026-03-28");
$diff = $d1->diff($d2);
$diff->days; // 86JSON
// Array → JSON
$json = json_encode(["name" => "Alice", "age" => 30]);
// '{"name":"Alice","age":30}'
json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
// JSON → Array
$data = json_decode($json, true); // true for associative arrayMiscellaneous
// Output (debugging)
print_r($array); // human-readable array output
var_dump($variable); // type and value in detail
// Regular expressions
preg_match('/(\d+)/', "abc123", $matches); // $matches[1] = "123"
preg_replace('/\s+/', " ", $str); // collapse multiple spaces
preg_split('/,\s*/', "a, b, c"); // ["a", "b", "c"]
// URL
http_build_query(["a" => 1, "b" => 2]); // "a=1&b=2"
parse_url("https://example.com/path?q=1"); // array of URL parts
// Passwords (recommended)
$hash = password_hash("mypassword", PASSWORD_BCRYPT);
$verify = password_verify("mypassword", $hash); // trueTips
Strict Type Mode
<?php
declare(strict_types=1);
function add(int $a, int $b): int {
return $a + $b;
}
add(1, "2"); // TypeError ← error when strict_types=1Nullsafe Operator (PHP 8.0+)
// ?-> safely handles null in a chain
$city = $user?->getAddress()?->getCity();
// Returns null if $user is null (no error)Named Arguments (PHP 8.0+)
function createUser(string $name, int $age = 0, string $role = "user"): array {
return compact("name", "age", "role");
}
// Call by argument name (order doesn't matter)
createUser(name: "Alice", role: "admin");Spread Operator
$a = [1, 2, 3];
$b = [4, 5, 6];
$merged = [...$a, ...$b]; // [1, 2, 3, 4, 5, 6]
// Spread array into function arguments
sum(...$a); // 6