PHPPHP

PHP: More snippets – code examples

Contents

Function with Types and Named Argument

Functions#function#return#named argumentsCompare in all languages
Use case: Bundle recurring logic, e.g. greeting texts, price calculation, formatting.
<?php
function begruesse(string $name, string $gruss = "Hello"): string {
    return "$gruss, $name!";
}
echo begruesse("Ada"), "\n";
echo begruesse("Linus", gruss: "Hi"), "\n";

Types for parameters and return value make the function self-documenting. Named arguments (gruss: "Moin") exist since PHP 8.

Named Arguments and Spread

Functions#named arguments#spread#parameter
Use case: Call functions with many optional parameters readably, e.g. for configuration objects.
<?php
function erstelleNutzer(string $name, int $alter = 18, bool $aktiv = true, string $rolle = "user"): string {
    return sprintf("%s (%d), active=%s, role=%s", $name, $alter, var_export($aktiv, true), $rolle);
}
echo erstelleNutzer("Ada", rolle: "admin"), "\n";
$optionen = ["alter" => 40, "aktiv" => false];
echo erstelleNutzer("Bob", ...$optionen), "\n";

Named arguments let you skip default values. An array with string keys can be unpacked as named arguments with ....

try / catch / finally

Error handling#try#catch#exception#errorCompare in all languages
Use case: Catch faulty calculations or input without the script aborting.
<?php
try {
    $x = intdiv(10, 0);
} catch (DivisionByZeroError $e) {
    echo "Error: ", $e->getMessage(), "\n";
} finally {
    echo "Cleaning up\n";
}

intdiv(10, 0) throws a DivisionByZeroError. finally always runs – ideal for closing resources.

Write and Read a File

Files#file#read file#file_put_contentsCompare in all languages
Use case: Save logs, configurations or text data and load them again.
<?php
file_put_contents("notizen.txt", "Line 1\nLine 2\n");
foreach (file("notizen.txt", FILE_IGNORE_NEW_LINES) as $zeile) {
    echo $zeile, "\n";
}

file_put_contents writes, file reads all lines into an array. For very large files it is better to read with fopen/fgets (or a generator).

Handling JSON

Files#json#json_decode#api
Use case: Exchange data with web APIs and JavaScript, read configuration files.
<?php
$daten = ["name" => "Ada", "sprachen" => ["PHP", "C"], "aktiv" => true];
$json = json_encode($daten, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
echo $json, "\n";

try {
    $zurueck = json_decode($json, true, 512, JSON_THROW_ON_ERROR);
    echo $zurueck["sprachen"][1], "\n";
    json_decode("{kaputt", true, 512, JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
    echo "JSON error: ", $e->getMessage(), "\n";
}

JSON_THROW_ON_ERROR triggers a JsonException for invalid JSON instead of silently returning null. true as the second parameter yields arrays instead of objects.

String Functions and Formatting

Strings#string#sprintf#number_format#mb_
Use case: Check, transform and format texts for display (prices, slugs).
<?php
$titel = "  Hello nice café  ";
$slug = strtolower(trim(preg_replace("/[^a-zA-Z0-9]+/", "-", $titel), "-"));
echo $slug, "\n";
var_dump(str_contains($titel, "café"));
echo mb_strtoupper(trim($titel)), "\n";
echo sprintf("Price: %s EUR", number_format(1234.5, 2, ",", ".")), "\n";
echo ucfirst("php"), " ", str_pad("7", 3, "0", STR_PAD_LEFT), "\n";
echo wordwrap("A long sentence", 8, "\n", true), "\n";

mb_* functions handle accented characters correctly. number_format, sprintf and str_pad format numbers. The simple slug expression replaces every run of non-letters with - (accented characters become separators in the process; real slugs need transliteration, e.g. via intl).

Regular Expression (preg)

Strings#regex#preg_match#pattern
Use case: Find and replace email addresses, phone numbers or patterns in text.
<?php
$text = "Contact: ada@example.com, bob@test.org";
preg_match_all("/[\w.]+@[\w.]+\.\w+/", $text, $treffer);
print_r($treffer[0]);
echo preg_replace("/\d+/", "#", "Phone 12345"), "\n";
if (preg_match("/^(\d{4})-(\d{2})-(\d{2})$/", "2026-03-15", $m)) {
    echo "Year: $m[1], Month: $m[2]\n";
}

preg_match_all returns all matches, preg_replace replaces patterns, parentheses form groups ($m[1]). The patterns are enclosed in delimiters (/.../).

PDO: Querying Data

Database#pdo#sql#prepared statement#sqlite
Use case: Read rows from MySQL/SQLite safely, e.g. look up users or display product lists.
<?php
$pdo = new PDO("sqlite::memory:", null, null, [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);
$pdo->exec("CREATE TABLE nutzer (id INTEGER PRIMARY KEY, name TEXT, jahre INTEGER)");
$ins = $pdo->prepare("INSERT INTO nutzer (name, jahre) VALUES (?, ?)");
foreach ([["Ada", 36], ["Bob", 25]] as $n) {
    $ins->execute($n);
}
$stmt = $pdo->prepare("SELECT name FROM nutzer WHERE jahre > :min ORDER BY name");
$stmt->execute(["min" => 30]);
print_r($stmt->fetchAll(PDO::FETCH_COLUMN));

An in-memory SQLite database is good for trying things out without a database server (requires the pdo_sqlite extension). The query uses a prepared statement with a named placeholder.

PDO: Transaction

Database#pdo#transaction#rollback
Use case: Execute related changes atomically, e.g. bank transfers or orders with stock levels.
<?php
function ueberweise(PDO $pdo, int $von, int $nach, int $betrag): void {
    try {
        $pdo->beginTransaction();
        $pdo->prepare("UPDATE konten SET saldo = saldo - ? WHERE id = ?")->execute([$betrag, $von]);
        $pdo->prepare("UPDATE konten SET saldo = saldo + ? WHERE id = ?")->execute([$betrag, $nach]);
        $pdo->commit();
    } catch (Throwable $e) {
        if ($pdo->inTransaction()) {
            $pdo->rollBack();
        }
        throw $e;
    }
}

On any error everything is rolled back – there is never a state in which money was debited but not credited. Prerequisite: ERRMODE_EXCEPTION.

Generator for Large Data

Advanced#yield#generator#iterator
Use case: Process large files or database results without holding everything in memory.
<?php
function zaehleBis(int $n): Generator {
    for ($i = 1; $i <= $n; $i++) {
        yield $i;
    }
}
foreach (zaehleBis(3) as $x) {
    echo $x, "\n";
}
echo array_sum(iterator_to_array(zaehleBis(100), false)), "\n";

yield pauses the function and delivers the next value. iterator_to_array(..., false) collects all values (keys are discarded). For very large amounts you iterate directly with foreach.