PHP: Basics – code examples
Contents
Hello World
Use case: A first test of whether PHP is installed correctly and runs.
<?php
echo "Hello World!\n";echo prints text. Run it with php datei.php or via the web server.
is a line break.
Variables and Types
Use case: Store values and check their type with gettype/var_dump.
<?php
$name = "Ada";
$alter = 36;
$groesse = 1.68;
$aktiv = true;
echo "$name, $alter, $groesse, " . var_export($aktiv, true) . "\n";
echo gettype($alter), " ", gettype($groesse), "\n";Variables start with $. gettype returns the type (integer, double for float). var_export prints true/false readably, because echo true only prints 1.
Null Coalescing and Nullsafe
Basics#??#nullsafe#null#default value
Use case: Handle missing form values or optional configuration with default values.
<?php
$eingabe = $_GET["name"] ?? "Guest";
echo "Hello $eingabe\n";
$konfig = [];
$konfig["debug"] ??= false;
var_dump($konfig["debug"]);
$nutzer = null;
echo $nutzer?->adresse?->stadt ?? "unknown", "\n";?? kicks in for a missing or null value, without a warning. ??= only assigns if nothing is set yet. ?-> short-circuits on null instead of throwing an error.
Date and Time with DateTimeImmutable
Basics#datetime#time#date#diff
Use case: Calculate deadlines, format timestamps, count days until an event.
<?php
$zone = new DateTimeZone("Europe/Berlin");
$jetzt = new DateTimeImmutable("2026-03-15 09:30", $zone);
echo $jetzt->format("d.m.Y H:i"), "\n";
echo $jetzt->modify("+30 days")->format("d.m.Y"), "\n";
$ziel = new DateTimeImmutable("2026-12-24 09:30", $zone);
echo $jetzt->diff($ziel)->days, " days until Christmas\n";DateTimeImmutable never changes itself (every method returns a new object) and is therefore safer than DateTime. Always set a time zone.