PHP
PHP 8+ cheat sheet covering modern syntax, types, enums, match expressions, named arguments, and web development best practices.
Other PHP Sheets
Setup & Basics
Getting started with PHP
Installing PHP and setting up development environment
# Install PHP 8.3
# macOS (Homebrew)
brew install php
# Ubuntu/Debian
sudo apt update && sudo apt install php8.3
# Check version
php -v
# Start built-in server
php -S localhost:8000
# Install Composer
curl -sS https://getcomposer.org/installer | phpBasic PHP syntax and structure
<?php
// Single line comment
/* Multi-line
comment */
// Variables (dynamic typing)
$name = "PHP";
$version = 8.3;
$isAwesome = true;
// Constants
const APP_NAME = "MyApp";
define('VERSION', '1.0.0');
// Output
echo "Hello $name";
print("Hello");
var_dump($variable);
// Include files
require 'config.php';
include 'header.php';PHP data types and type declarations
// Scalar types
$string = "text";
$int = 42;
$float = 3.14;
$bool = true;
// Compound types
$array = [1, 2, 3];
$object = new stdClass();
// Type declarations (PHP 7+)
function add(int $a, int $b): int {
return $a + $b;
}
// Nullable types (PHP 7.1+)
function find(?int $id): ?User {
return $id ? User::find($id) : null;
}
// Union types (PHP 8.0+)
function process(int|float $number): string|false {
return $number > 0 ? "positive" : false;
}Control Structures
Conditionals, loops, and control flow
If statements, switch, and match expressions
// If statement
if ($age >= 18) {
echo "Adult";
} elseif ($age >= 13) {
echo "Teen";
} else {
echo "Child";
}
// Ternary operator
$status = $age >= 18 ? 'adult' : 'minor';
// Null coalescing (PHP 7+)
$name = $_GET['name'] ?? 'Guest';
// Match expression (PHP 8+)
$result = match($status) {
'pending' => 'Waiting',
'active' => 'Ready',
'closed' => 'Done',
default => 'Unknown'
};Different types of loops in PHP
// For loop
for ($i = 0; $i < 10; $i++) {
echo $i;
}
// Foreach loop
foreach ($array as $value) {
echo $value;
}
foreach ($array as $key => $value) {
echo "$key: $value";
}
// While loop
while ($condition) {
// code
}
// Do-while loop
do {
// code
} while ($condition);Functions & Closures
Functions, closures, and arrow functions
Function declaration and parameters
// Basic function
function greet($name) {
return "Hello, $name!";
}
// Type hints and return types
function add(int $a, int $b): int {
return $a + $b;
}
// Default parameters
function connect($host = 'localhost', $port = 3306) {
// connection logic
}
// Variadic functions
function sum(...$numbers): float {
return array_sum($numbers);
}
// Named arguments (PHP 8+)
connect(port: 8080, host: 'example.com');Anonymous functions and arrow functions
// Closure (anonymous function)
$greet = function($name) {
return "Hello, $name";
};
// Closure with use
$message = 'Hello';
$say = function($name) use ($message) {
return "$message, $name";
};
// Arrow function (PHP 7.4+)
$add = fn($a, $b) => $a + $b;
// Array operations with arrow functions
$numbers = [1, 2, 3];
$doubled = array_map(fn($n) => $n * 2, $numbers);Arrays
Array manipulation and operations
Creating and accessing arrays
// Indexed array
$numbers = [1, 2, 3, 4, 5];
$colors = array('red', 'green', 'blue');
// Associative array
$person = [
'name' => 'John',
'age' => 30,
'email' => 'john@example.com'
];
// Multidimensional array
$matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
// Accessing elements
echo $numbers[0]; // 1
echo $person['name']; // John
echo $matrix[1][2]; // 6Built-in array manipulation functions
// Common array functions
$numbers = [3, 1, 4, 1, 5];
// Sorting
sort($numbers); // [1, 1, 3, 4, 5]
rsort($numbers); // Reverse sort
// Array operations
$sum = array_sum($numbers);
$unique = array_unique($numbers);
$filtered = array_filter($numbers, fn($n) => $n > 2);
$mapped = array_map(fn($n) => $n * 2, $numbers);
// Search and check
$key = array_search(4, $numbers);
$exists = in_array(3, $numbers);Object-Oriented PHP
Classes, objects, and OOP concepts
Basic class definition and object creation
class User {
public string $name;
private int $age;
public function __construct(string $name, int $age) {
$this->name = $name;
$this->age = $age;
}
public function greet(): string {
return "Hello, I'm {$this->name}";
}
}
// Create object
$user = new User('John', 30);
echo $user->greet();Extending classes and implementing interfaces
// Interface
interface Payable {
public function pay(float $amount): bool;
}
// Abstract class
abstract class Employee {
abstract public function calculateSalary(): float;
}
// Inheritance
class Developer extends Employee implements Payable {
public function calculateSalary(): float {
return 5000.00;
}
public function pay(float $amount): bool {
return true;
}
}PHP 8 Features
Modern PHP 8+ features and improvements
Major features introduced in PHP 8.0
// Named arguments
function createUser($name, $email, $role = 'user') {
// ...
}
createUser(email: 'john@example.com', name: 'John');
// Union types
function processValue(int|string $value): void {
// ...
}
// Match expression
$result = match($value) {
1, 2 => 'low',
3, 4, 5 => 'medium',
default => 'high'
};
// Nullsafe operator
$country = $user?->getAddress()?->getCountry();Enums, readonly, first-class callables, readonly classes
// Enums (PHP 8.1)
enum Status {
case PENDING;
case ACTIVE;
case ARCHIVED;
}
// Readonly properties (PHP 8.1)
class User {
public function __construct(
public readonly string $id
) {}
}
// First-class callables (PHP 8.1)
$fn = strlen(...);
// Readonly classes (PHP 8.2)
readonly class Config {
public function __construct(
public string $apiKey
) {}
}Typed class constants, #[\Override], json_validate, dynamic class constants
// Typed class constants (PHP 8.3)
class Config {
const string VERSION = '1.0.0';
const int MAX_USERS = 100;
}
// #[\Override] attribute (PHP 8.3)
class Base {
public function greet(): string {
return 'Hello';
}
}
class Child extends Base {
#[\Override]
public function greet(): string {
return 'Hi';
}
}
// json_validate() (PHP 8.3)
if (json_validate($jsonString)) {
$data = json_decode($jsonString, true);
}
// Dynamic class constants (PHP 8.3)
class Status {
const ACTIVE = 'active';
const INACTIVE = 'inactive';
}
$name = 'ACTIVE';
echo Status::{$name}; // 'active'Property hooks, asymmetric visibility, new array helpers
// Property hooks (PHP 8.4) — get/set without a backing function
class User {
public string $fullName {
get => "{$this->first} {$this->last}";
set => trim($value);
}
public function __construct(
public string $first,
public string $last,
) {}
}
// Asymmetric visibility (PHP 8.4)
class Post {
public private(set) string $id = '';
public protected(set) int $views = 0;
}
// New array functions (PHP 8.4)
$first = array_find($users, fn($u) => $u->isActive);
$any = array_any($users, fn($u) => $u->isAdmin);
$all = array_all($users, fn($u) => $u->isVerified);
// Chain new without parens (PHP 8.4)
$slug = new Slugger()->slugify($title);Error Handling
Exception handling and error management
Working with exceptions and try-catch blocks
// Basic exception handling
try {
$result = riskyOperation();
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
}
// Multiple catch blocks
try {
$data = processData();
} catch (InvalidArgumentException $e) {
// Handle invalid argument
} catch (RuntimeException $e) {
// Handle runtime error
} finally {
// Always executes
cleanup();
}Database & PDO
Database connections and operations with PDO
Connecting to databases and executing queries
// Connect to database
$pdo = new PDO(
'mysql:host=localhost;dbname=mydb',
'username',
'password'
);
// Prepared statement
$stmt = $pdo->prepare('SELECT * FROM users WHERE id = :id');
$stmt->execute(['id' => $userId]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);
// Insert data
$stmt = $pdo->prepare('INSERT INTO users (name, email) VALUES (?, ?)');
$stmt->execute([$name, $email]);String Manipulation
Working with strings in PHP
Common string manipulation functions
// String length and case
$length = strlen($string);
$upper = strtoupper($string);
$lower = strtolower($string);
// String search
$pos = strpos($haystack, 'needle');
$contains = str_contains($text, 'word');
// String manipulation
$trimmed = trim($string);
$replaced = str_replace('old', 'new', $string);
$substring = substr($string, 0, 10);
// Explode and implode
$parts = explode(',', $csv);
$joined = implode(' | ', $array);File Handling
Reading and writing files
Working with files and directories
// Read file
$content = file_get_contents('file.txt');
$lines = file('file.txt', FILE_IGNORE_NEW_LINES);
// Write file
file_put_contents('file.txt', $data);
file_put_contents('log.txt', $data, FILE_APPEND);
// File info
if (file_exists($file)) {
$size = filesize($file);
$modified = filemtime($file);
}
// Directory operations
$files = scandir($directory);
mkdir('new_directory', 0755, true);Web Features
Sessions, cookies, and HTTP handling
Managing user sessions and cookies
// Sessions
session_start();
$_SESSION['user_id'] = 123;
$_SESSION['username'] = 'john';
// Check session
if (isset($_SESSION['user_id'])) {
// User is logged in
}
// Cookies
setcookie('name', 'value', time() + 3600);
$value = $_COOKIE['name'] ?? null;
// Headers
header('Content-Type: application/json');
header('Location: /dashboard');Working with JSON and building APIs
// JSON encoding
$json = json_encode($data);
$json = json_encode($data, JSON_PRETTY_PRINT);
// JSON decoding
$data = json_decode($json); // Object
$array = json_decode($json, true); // Array
// API response
header('Content-Type: application/json');
echo json_encode(['status' => 'success']);
// Handle JSON input
$input = json_decode(file_get_contents('php://input'), true);Advanced Features
Generators, regex, and namespaces
Memory-efficient iteration with generators
// Simple generator
function getNumbers() {
for ($i = 1; $i <= 3; $i++) {
yield $i;
}
}
foreach (getNumbers() as $number) {
echo $number;
}
// Generator with keys
function getUsers() {
yield 'admin' => 'Alice';
yield 'user' => 'Bob';
}Pattern matching with regex
// Match pattern
if (preg_match('/\d+/', $text, $matches)) {
echo $matches[0]; // First match
}
// Match all
preg_match_all('/\w+/', $text, $matches);
// Replace
$result = preg_replace('/\s+/', ' ', $text);
// Split
$parts = preg_split('/[,;]/', $text);