PHP Cheatsheet

Syntax, variables, arrays, functions, OOP & common patterns

Language
Contents
📝

Basics

<?php
// Variables ($ prefix, loosely typed)
$name = "Alice";
$age = 25;
$pi = 3.14;
$active = true;
$nothing = null;

// Constants
define("MAX", 100);
const PI = 3.14159;

// Type casting
$int = (int) "42";
$str = (string) 42;

// Type checking
gettype($name);     // "string"
is_string($name);   // true
is_array($arr);     // true/false
isset($x);          // is set & not null
empty($x);          // is empty/falsy

// Output
echo "Hello $name";
print_r($arr);        // readable array
var_dump($x);          // type + value
📄

Strings

$s = "Hello World";
strlen($s);                // 11
strtoupper($s);            // HELLO WORLD
strtolower($s);            // hello world
substr($s, 0, 5);         // Hello
str_replace("World", "PHP", $s);
strpos($s, "World");      // 6
trim($s);   ltrim($s);   rtrim($s);
explode(" ", $s);          // split → array
implode(",", $arr);        // join → string
sprintf("Hi %s, age %d", $name, $age);

// Heredoc
$html = <<<HTML
<h1>Hello $name</h1>
HTML;
📦

Arrays

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

// Associative array
$user = ["name" => "Alice", "age" => 25];
$user["name"];

// Array functions
array_push($arr, "val");
array_pop($arr);
array_shift($arr);     // remove first
array_merge($a, $b);
array_keys($arr);
array_values($arr);
in_array("apple", $fruits);
array_map(fn($x) => $x * 2, $nums);
array_filter($nums, fn($x) => $x > 5);
sort($arr);   rsort($arr);   usort($arr, $cmp);

Functions

function greet(string $name): string {
    return "Hello, $name!";
}

// Default params
function add(int $a, int $b = 0): int {
    return $a + $b;
}

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

// Closure
$greet = function($name) use ($prefix) {
    return "$prefix $name";
};

// Variadic
function sum(int ...$nums): int {
    return array_sum($nums);
}

// Nullable return
function find(int $id): ?User { }
🏗️

OOP

class User {
    public function __construct(
        private string $name,
        private int $age = 0
    ) {}
    public function getName(): string {
        return $this->name;
    }
}

// Inheritance
class Admin extends User {
    public function __construct(string $name) {
        parent::__construct($name, 0);
    }
}

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

// Trait
trait Timestampable {
    public DateTime $createdAt;
}

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

Control Flow

// Match (PHP 8+)
$result = match($status) {
    "active" => "User is active",
    "banned" => "User is banned",
    default => "Unknown",
};

// Null coalescing
$name = $_GET["name"] ?? "Guest";

// Null safe operator
$city = $user?->getAddress()?->city;

// Foreach
foreach ($arr as $val) { }
foreach ($arr as $key => $val) { }

// Try/catch
try { } catch (Exception $e) {
    echo $e->getMessage();
} finally { }
📁

File I/O

file_get_contents("file.txt");
file_put_contents("file.txt", $data);
file_put_contents("file.txt", $data, FILE_APPEND);
file_exists("file.txt");
is_file("file.txt");
unlink("file.txt");          // delete
rename("old.txt", "new.txt");
file("file.txt");             // array of lines

// JSON
json_encode($data);
json_decode($json, true);   // assoc array
🌐

Web / HTTP

// Superglobals
$_GET["id"]         // query params
$_POST["name"]      // form data
$_SESSION["user"]   // session
$_COOKIE["token"]   // cookies
$_SERVER["REQUEST_METHOD"]
$_FILES["upload"]   // uploaded file

// Headers
header("Content-Type: application/json");
header("Location: /dashboard");
http_response_code(404);

// Session
session_start();
$_SESSION["user"] = "Alice";
session_destroy();