PHP logoPHPv8.5BEGINNER

PHP

PHP 8+ cheat sheet covering modern syntax, types, enums, match expressions, named arguments, and web development best practices.

12 min read
phpphp8backendweblaravelsymfonycomposeroop

Other PHP Sheets

Loading your progress

Setup & Basics

Getting started with PHP

Installing PHP and setting up development environment

php
# 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 | php
🚀 PHP 8.3 brings major performance improvements
📦 Composer is the standard dependency manager
🔧 Built-in server perfect for development
⚡ PHP-FPM recommended for production

Basic PHP syntax and structure

php
<?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 files start with <?php tag
📌 Variables always start with $ sign
⚡ Use require for critical files, include for optional
🔥 Constants are globally accessible and immutable

Data Types

PHP data types and type declarations

php
// 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;
}
💡 PHP is dynamically typed but supports type hints
⚡ Use strict_types=1 for type safety
📌 Union types allow multiple possible types
🔥 Never type indicates function never returns

Control Structures

Conditionals, loops, and control flow

Conditionals

If statements, switch, and match expressions

php
// 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'
};
💡 Match is stricter than switch (no type coercion)
⚡ Null coalescing (??) simplifies default values
📌 Match returns values, switch executes code
🔥 Alternative syntax cleaner for templates

Loops

Different types of loops in PHP

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);
💡 Use foreach for arrays, for when you need index
⚡ Reference (&) in foreach allows modification
📌 Always unset references after foreach
🔥 Break/continue can specify nesting level

Functions & Closures

Functions, closures, and arrow functions

Functions

Function declaration and parameters

php
// 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');
💡 Named arguments improve readability
⚡ Variadic functions accept unlimited arguments
📌 Pass by reference with & to modify variables
🔥 Type hints catch errors early

Anonymous functions and arrow functions

php
// 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);
💡 Arrow functions auto-capture parent scope
⚡ Use & to modify external variables in closures
📌 Arrow functions always return (no void)
🔥 First-class callables simplify syntax in PHP 8.1+

Arrays

Array manipulation and operations

Array Basics

Creating and accessing arrays

php
// 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];  // 6
💡 Use [] syntax for arrays (modern PHP)
⚡ Spread operator (...) unpacks arrays
📌 array_key_exists vs isset: isset returns false for null
🔥 Destructuring makes code cleaner

Array Functions

Built-in array manipulation functions

php
// 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);
💡 array_map transforms, array_filter selects, array_reduce aggregates
⚡ Spaceship operator (<=>) simplifies comparisons
📌 array_merge re-indexes, + operator preserves keys
🔥 array_column great for extracting from multi-dimensional arrays

Object-Oriented PHP

Classes, objects, and OOP concepts

Basic class definition and object creation

php
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();
💡 Constructor property promotion reduces boilerplate
⚡ Readonly properties ensure immutability
📌 Use visibility modifiers for encapsulation
🔥 Static properties/methods shared across all instances

Extending classes and implementing interfaces

php
// 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;
    }
}
💡 Interfaces define contracts, abstract classes provide partial implementation
⚡ Traits enable horizontal code reuse
📌 Use final to prevent inheritance
🔥 Late static binding with static:: for proper inheritance

PHP 8 Features

Modern PHP 8+ features and improvements

Major features introduced in PHP 8.0

php
// 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();
💡 Match expressions are safer than switch (no fall-through)
⚡ Nullsafe operator prevents null reference errors
📌 Constructor promotion reduces boilerplate significantly
🔥 JIT compilation dramatically improves CPU-intensive tasks

Enums, readonly, first-class callables, readonly classes

php
// 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
    ) {}
}
💡 Enums provide type-safe constants with methods
⚡ Readonly properties/classes ensure immutability
📌 First-class callables simplify functional programming
🔥 Fibers enable async programming without callbacks

Typed class constants, #[\Override], json_validate, dynamic class constants

php
// 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'
💡 Typed class constants prevent subclasses from drifting on type
📌 #[\Override] catches typos when refactoring parent classes
⚡ json_validate is cheaper than json_decode just to test validity
🟢 Dynamic class constants mirror dynamic property access
php8.3featuresmodern

Property hooks, asymmetric visibility, new array helpers

php
// 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);
💡 Property hooks replace boilerplate getter/setter pairs
📌 Asymmetric visibility = public read, restricted write
⚡ array_find / array_any / array_all are finally built-in
🟢 `new Foo()->bar()` no longer needs the extra parentheses
php8.4featuresmodern

Error Handling

Exception handling and error management

Exceptions

Working with exceptions and try-catch blocks

php
// 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();
}
💡 Use specific exception types for different errors
⚡ Finally block always executes for cleanup
📌 Chain exceptions to preserve error context
🔥 Throwable catches both Exception and Error types

Database & PDO

Database connections and operations with PDO

PDO Basics

Connecting to databases and executing queries

php
// 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]);
💡 Always use prepared statements to prevent SQL injection
⚡ Use transactions for related operations
📌 PDO supports multiple databases with same interface
🔥 Set PDO::ERRMODE_EXCEPTION for better error handling

String Manipulation

Working with strings in PHP

Common string manipulation functions

php
// 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);
💡 Use mb_* functions for multibyte (UTF-8) strings
⚡ str_contains/starts_with/ends_with are PHP 8.0+ additions
📌 Always use htmlspecialchars() for user input in HTML
🔥 Heredoc parses variables, Nowdoc does not

File Handling

Reading and writing files

File Operations

Working with files and directories

php
// 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);
💡 Use file_get_contents for simple reads, handles for large files
⚡ Always check file_exists() before operations
📌 Use LOCK_EX flag to prevent race conditions
🔥 Set proper permissions (0755 for dirs, 0644 for files)

Web Features

Sessions, cookies, and HTTP handling

Managing user sessions and cookies

php
// 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');
💡 session_start() must be called before any output
⚡ Use secure, httponly, and samesite for cookie security
📌 Always exit() after header redirects
🔥 Regenerate session ID after login to prevent fixation

JSON & APIs

Working with JSON and building APIs

php
// 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);
💡 Always validate JSON with json_last_error()
⚡ Use php://input for raw POST data
📌 Set proper Content-Type and status codes
🔥 json_validate() in PHP 8.3+ checks without decoding

Advanced Features

Generators, regex, and namespaces

Memory-efficient iteration with generators

php
// 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';
}
💡 Generators use yield to pause and resume execution
⚡ Perfect for processing large datasets with low memory
📌 yield from delegates to another generator
🔥 Generators maintain state between iterations

Pattern matching with regex

php
// 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);
💡 Use preg_quote() to escape user input in patterns
⚡ Named groups make matches more readable
📌 Add pattern modifiers: i (case), m (multiline), s (dotall)
🔥 preg_replace_callback for complex replacements

More PHP Cheat Sheets