PHPPHP
BeginnerLesson 2 of 16

Variables, Types & Strings – PHP

Variables with $, the basic types and the difference between '...' and "...".

Variables always start with $. You do not declare a type, PHP detects it on its own. With var_dump() you see type and value – the most important debugging tool at the beginning.

<?php
$name = "Ada";        // string
$alter = 36;          // int
$groesse = 1.68;      // float
$aktiv = true;        // bool
$nichts = null;       // null
var_dump($name, $alter, $groesse, $aktiv, $nichts);
echo gettype($alter), "\n";   // integer

In double quotes, variables are inserted (interpolation) and escape sequences like are evaluated. In single quotes, everything stays literal. Strings are concatenated with the dot.

<?php
$name = "Ada"; $alter = 36;
echo "Name: $name, Age: $alter\n";
echo 'Name: $name\n';
echo "\n";
$p = ["stadt" => "Bonn"];
echo "City: {$p['stadt']}\n";       // expressions in curly braces
echo "Sum: " . (1 + 2) . "\n";     // dot = concatenation

Numbers, constants and type conversions (casts):

<?php
const MWST = 0.19;
define("APP_NAME", "Demo");
$n = (int) "42abc";        // 42
$f = (float) "3.5";        // 3.5
$s = (string) 7;           // "7"
echo 7 / 2, " ", intdiv(7, 2), " ", 7 % 2, " ", 2 ** 10, "\n";   // 3.5 3 1 1024
var_dump("10" == "1e1");   // bool(true)  (both are numeric)
var_dump(0 == "a");        // bool(false) since PHP 8
var_dump("abc" === "abc"); // bool(true)
Warning== compares with type conversion (type juggling) and sometimes gives surprising results. When in doubt, always use === and !==.
TipHeredoc syntax allows multi-line text with interpolation: <<<TEXT ... TEXT;. Nowdoc (<<<'TEXT') behaves like single quotes.