PHPPHP

PHP cheatsheet – syntax overview

93 key commands and patterns for quick reference.

Basics Operators Control flow Arrays Strings Functions Classes & OOP Enums, match & Modern Syntax Errors, Files & JSON Web, Database & Security Composer & Command Line

Basics

<?php echo "Text", $var;Start a PHP block and print output
<?= $var ?>Short form of echo in an HTML template
$name = "Ada";Create a variable (always with $)
const PI = 3.14; define("X", 1);Define constants
var_dump($x); print_r($arr);Show type and value for debugging
declare(strict_types=1);Strict type checking for the file (first statement)
// comment # comment /* ... */Comment variants

Operators

+ - * / % ** intdiv(7, 2)Arithmetic: division returns float, intdiv returns an integer
$a . $b $a .= "x"Concatenate strings
=== !== == != < > <= >=Comparisons (=== strict, == with type conversion)
$a <=> $bSpaceship: -1, 0 or 1 (for sorting)
$x ?? "default"Null coalescing: fallback for null/unset
$x ??= 5; $o?->propAssign if null / nullsafe access
&& || ! and or xorLogical operators

Control flow

if (...) { } elseif (...) { } else { }Branching
$r = match ($x) { 1, 2 => "a", default => "b" };match expression (strict, throws on a missing case)
for ($i = 0; $i < 5; $i++) { }Counting loop
foreach ($arr as $k => $v) { }Iterate over an array (key optional)
while (...) { } do { } while (...);Loop with a condition
break; continue; exit;End loop / next round / end script
$ok ? "ja" : "nein"Ternary operator

Arrays

$l = [1, 2, 3]; $l[] = 4;Create an array and append
$m = ["a" => 1, "b" => 2];Associative array (map)
count($a) array_sum($a) max($a) min($a)Count, sum, maximum, minimum
in_array($x, $a, true) array_key_exists("k", $a)Is the value or key present?
array_map(fn($x) => $x * 2, $a)Transform every element
array_filter($a, fn($x) => $x > 1)Filter (keys are preserved)
array_reduce($a, fn($c, $x) => $c + $x, 0)Reduce to a single value
sort($a) rsort($a) asort($a) ksort($a) usort($a, $fn)Sort (value / key / custom function)
array_merge($a, $b) [...$a, ...$b]Merge arrays
array_keys($a) array_values($a) array_unique($a)Keys, values, remove duplicates
array_slice($a, 1, 2) array_splice($a, 1, 1)Read / remove a portion
[$x, $y] = [1, 2]; ["k" => $v] = $m;Destructuring

Strings

strlen($s) mb_strlen($s)Length in bytes / in characters
strtolower($s) mb_strtoupper($s) ucfirst($s)Upper/lower case
trim($s) ltrim($s) rtrim($s)Remove whitespace
explode(",", $s) implode(",", $arr)Split / join
str_replace("a", "b", $s)Replace
str_contains($s, "x") str_starts_with($s, "x") str_ends_with($s, "x")Contains / starts with / ends with (PHP 8)
substr($s, 0, 3) mb_substr($s, 0, 3)Substring
strpos($s, "x")Find position (false if not found – check with ===)
sprintf("%05.2f %s %d", 3.14159, "x", 7)Formatted string
number_format(1234.5, 2, ",", ".")Format a number: 1.234,50
preg_match("/^\d+$/", $s) preg_replace("/\s+/", " ", $s)Regular expressions

Functions

function f(int $a, int $b = 2): int { return $a + $b; }Function with types and a default value
f(b: 5, a: 1)Named arguments
function f(int ...$zahlen) { } f(...$arr)Variadic and spread
fn($x) => $x * 2Arrow function (captures outer variables automatically)
function () use ($x) { return $x; }Closure with use
function f(?string $s): int|string|null { }Nullable and union types
$f = strlen(...); $g = $obj->methode(...);First-class callable syntax (8.1)

Classes & OOP

class A { public function __construct(private int $x) {} }Class with constructor promotion
class B extends A implements I { use T; }Inheritance, interface, trait
public / protected / privateVisibility
public readonly string $name;Property that can only be set once (8.1)
static function f() {} self::$x static::classStatic members, current class
$this->x parent::__construct()Own object / parent class
$o instanceof ACheck the type of an object
abstract class X {} final class Y {} interface I {}Abstract, not extendable, contract
clone $objCopy an object (shallow)

Enums, match & Modern Syntax

enum S: string { case A = "a"; case B = "b"; }Backed enum (8.1)
S::from("a") S::tryFrom("z") S::cases()Enum from value / with null / all cases
$e->name $e->valueName and value of an enum case
#[Attribute] #[Route("/")]Attributes (8.0)
readonly class P { }Make the whole class immutable (8.2)
function f(): never { throw new Exception(); }Return type never: never returns
$x = $a ?? throw new Exception("fehlt");throw as an expression (8.0)

Errors, Files & JSON

try { } catch (A | B $e) { } finally { }Error handling with multi-catch
throw new InvalidArgumentException("Text");Throw an exception
$e->getMessage() $e->getCode() $e->getTraceAsString()Information about the exception
file_get_contents($p) file_put_contents($p, $s, FILE_APPEND)Read / write a whole file
file($p, FILE_IGNORE_NEW_LINES)Lines as an array
file_exists($p) is_readable($p) unlink($p)Check / delete
json_encode($x, JSON_PRETTY_PRINT) json_decode($s, true, 512, JSON_THROW_ON_ERROR)Generate / parse JSON
__DIR__ __FILE__ basename($p)Current folder / file / file name

Web, Database & Security

$_GET["x"] ?? "" $_POST["x"] ?? ""URL and form parameters (unchecked!)
$_SERVER["REQUEST_METHOD"]HTTP method of the request
filter_var($s, FILTER_VALIDATE_EMAIL)Validate an email (or INT, URL ...)
header("Location: /ziel.php"); exit;Redirect
session_start(); $_SESSION["k"] = "v";Use a session (before any output)
htmlspecialchars($s, ENT_QUOTES)Escape HTML (XSS protection)
$stmt = $pdo->prepare("... WHERE id = ?"); $stmt->execute([$id]);Safe SQL query with a prepared statement
$stmt->fetch() $stmt->fetchAll()Fetch one row / all rows
password_hash($pw, PASSWORD_DEFAULT) password_verify($pw, $hash)Hash / verify a password
bin2hex(random_bytes(32))Cryptographically secure token

Composer & Command Line

php datei.phpRun a script in the terminal
php -S localhost:8000 -t publicStart the development server
php -l datei.phpCheck syntax (lint)
composer require vendor/paketInstall a package
composer install composer updateDependencies according to the lock file / update
require __DIR__ . "/vendor/autoload.php";Include the Composer autoloader
namespace App\Model; use App\Model\User;Declare a namespace / import a class
composer auditShow known security vulnerabilities in dependencies