📋 Cheat Sheets

PHP Cheat Sheet — Syntax, Arrays, and Common Patterns


Click any item to expand the explanation and examples.

📝 Basics

Variables and types basics
<?php
// Variables start with $
$name = "Alice";
$age = 30;
$price = 19.99;
$active = true;
$nothing = null;

// Type checking gettype($name); // “string” is_string($name); // true is_int($age); // true isset($name); // true (exists and not null) empty($name); // false

// Type casting $num = (int) “42”; $str = (string) 42; $float = (float) “3.14”;

// Constants define(‘MAX_SIZE’, 100); const APP_NAME = ‘MyApp’;

// String interpolation echo “Hello $name”; echo “Hello {$name}!”; echo ‘No $interpolation here’; // Single quotes = literal

String functions basics
strlen($str)                    // Length
strtolower($str)                // Lowercase
strtoupper($str)                // Uppercase
trim($str)                      // Remove whitespace
str_contains($str, "hello")     // Contains (PHP 8+)
str_starts_with($str, "Hello")  // Starts with (PHP 8+)
str_replace("old", "new", $str) // Replace
substr($str, 0, 5)              // Substring
explode(",", $str)              // Split → array
implode(", ", $arr)             // Join array → string
sprintf("Hello %s, age %d", $name, $age)

📦 Arrays

Indexed and associative arrays arrays
// Indexed array
$fruits = ["apple", "banana", "cherry"];
$fruits[] = "date";          // Append
$fruits[0];                  // "apple"
count($fruits);              // 4

// Associative array (like a dict/map) $user = [ “name” => “Alice”, “email” => “alice@example.com”, “age” => 30, ]; $user[“name”]; // “Alice” $user[“role”] = “admin”; // Add key

// Check key exists array_key_exists(“name”, $user); // true isset($user[“name”]); // true

// Common functions sort($fruits); // Sort (modifies in place) array_push($fruits, “elderberry”); array_pop($fruits); // Remove last in_array(“apple”, $fruits); // Contains array_merge($arr1, $arr2); // Merge array_keys($user); // [“name”, “email”, “age”] array_values($user); // [“Alice”, “alice@…”, 30]

// Array destructuring (PHP 7.1+) [$first, $second] = $fruits; [“name” => $name, “age” => $age] = $user;

Array functions (map, filter, reduce) arrays
$nums = [1, 2, 3, 4, 5];

// Map $doubled = array_map(fn($n) => $n * 2, $nums); // [2, 4, 6, 8, 10]

// Filter $evens = array_filter($nums, fn($n) => $n % 2 === 0); // [2, 4]

// Reduce $sum = array_reduce($nums, fn($carry, $n) => $carry + $n, 0); // 15

// Foreach foreach ($user as $key => $value) { echo “$key: $value\n”; }

⚙️ Functions

Functions and arrow functions functions
// Basic function
function greet(string $name): string {
    return "Hello, $name!";
}

// Default parameters function connect(string $host = “localhost”, int $port = 3306): void { // … }

// Nullable types function findUser(int $id): ?User { return null; // Can return User or null }

// Arrow functions (PHP 7.4+) $double = fn($x) => $x * 2;

// Spread operator function sum(int …$nums): int { return array_sum($nums); } sum(1, 2, 3, 4); // 10

// Named arguments (PHP 8+) connect(port: 5432, host: “db.example.com”);

🏗️ OOP

Classes (PHP 8+) oop
class User {
    // Constructor promotion (PHP 8+)
    public function __construct(
        private string $name,
        private string $email,
        private int $age = 0,
    ) {}
public function getName(): string {
    return $this->name;
}

}

$user = new User(“Alice”, “alice@example.com”, 30);

// Interface interface Printable { public function toString(): string; }

// Enum (PHP 8.1+) enum Status: string { case Active = ‘active’; case Inactive = ‘inactive’; }

// Match expression (PHP 8+) $label = match($status) { Status::Active => ‘Active’, Status::Inactive => ‘Inactive’, };

⚠️ Error Handling

try/catch and null safety errors
try {
    $result = riskyOperation();
} catch (InvalidArgumentException $e) {
    echo "Invalid: " . $e->getMessage();
} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
} finally {
    // Always runs
}

// Null coalescing $name = $user[“name”] ?? “Anonymous”;

// Nullsafe operator (PHP 8+) $city = $user?->getAddress()?->getCity();