PHP Variables and Data Types
AI-assistedDrafted with AI assistance and reviewed before publishing; examples are version-pinned. Verify against official docs when in doubt.
PHP is loosely typed: variables carry no declared type. That does not mean types do not matter — most surprising PHP behaviour comes from implicit conversion. This chapter sets the ground rules.
Environment
Check the version (examples target PHP 8.4 and run on any 8.x):
php -v
# PHP 8.4.x (cli)
Save examples as demo.php and run them with php demo.php. For web examples the built-in server is enough:
php -S localhost:8000
Open http://localhost:8000/demo.php — no Nginx or Apache needed.
Variables: the $ prefix
<?php
$name = "ann";
$age = 30;
$price = 9.9;
Variable names start with $ and are case-sensitive ($name and $Name are different variables). Use snake_case, not camelCase — that is both the PHP ecosystem’s own style and what PSR conventions assume.
There is no declaration step; assignment creates the variable. But reading an undefined variable yields null plus a warning:
echo $city; // Warning: Undefined variable $city, prints nothing
Assign before use, and check with isset() when a variable may be missing.
Four scalar types
$int = 42; // int
$float = 3.14; // float
$string = "hello"; // string
$bool = true; // bool
Plus two “special” types and two compound ones:
$nothing = null; // null: no value
$list = [1, 2, 3]; // array (see the next chapter)
Use var_dump() when debugging — it shows both type and value, which echo does not:
var_dump(42); // int(42)
var_dump("42"); // string(2) "42"
var_dump(3.0); // float(3)
var_dump(true); // bool(true)
var_dump(null); // NULL
Type-checking helpers:
is_int(42); // true
is_string("42"); // true
is_float(3.14); // true
is_bool(true); // true
is_null(null); // true
is_array([1]); // true
is_numeric("42"); // true — the string looks like a number
Strings: single versus double quotes
$name = "ann";
echo 'hello $name'; // hello $name — single quotes do not interpolate
echo "hello $name"; // hello ann
echo "hello {$name}!"; // hello ann! — braces delimit the variable name
Concatenation uses ., not +:
echo "hello " . $name; // hello ann
$total = "Total: " . 3 . " items";
Concatenating with + gives 0 (plus a warning). It is the single most common beginner mistake in PHP.
Arrays: PHP’s workhorse container
One type covers both lists and dictionaries:
$list = [1, 2, 3]; // indexed
$user = ["name" => "ann", "age" => 30]; // associative
$mixed = [1, "name" => "ann"]; // legal, but avoid
Reading and writing:
echo $list[0]; // 1
echo $user["name"]; // ann
$user["city"] = "Shenzhen"; // add
unset($user["age"]); // remove
A missing key produces null plus a warning, so fall back explicitly:
echo $user["nickname"] ?? "anonymous"; // null coalescing
Loose comparison: == versus ===
"42" == 42 // true — types are coerced first
"42" === 42 // false — types must match too
PHP 8 made numeric-string comparison saner, but == still has edges:
0 == "abc" // false since PHP 8 (it was true in PHP 7)
"" == null // true
false == "" // true
[] == false // true
Rule: always use ===, especially anywhere 0 and "" must be distinguishable.
Automatic type conversion
"10" + 5 // 15
"10abc" + 5 // 15 plus a Warning for the non-numeric string
"3.5" * 2 // 7.0
Convert explicitly when conversion is what you want:
$count = (int) "42"; // 42
$text = (string) 42; // "42"
$flag = (bool) ""; // false
Falsy values
These evaluate to false in a boolean context; everything else is true:
false, 0, 0.0, "", "0", [], null
Note that "0" is falsy in PHP, unlike most other languages:
if ("0") {
echo "runs";
} else {
echo "skipped"; // this branch actually runs
}
To test for a non-empty string use strlen($s) > 0 or $s !== "", not if ($s).
declare(strict_types=1)
By default PHP coerces argument types at call time:
function add(int $a, int $b): int {
return $a + $b;
}
add("3", "4"); // 7 — the strings were coerced
With strict types at the top of the file, wrong types raise TypeError:
<?php
declare(strict_types=1);
function add(int $a, int $b): int {
return $a + $b;
}
add("3", "4"); // TypeError
Put declare(strict_types=1); in every new file. It turns silent coercion into an explicit error. It applies per file, to the calls made from that file.
Variable scope
$global = "outer";
function show() {
echo $global; // Warning: Undefined variable $global
}
Functions do not see global variables. Declare it if you must:
function show(): void {
global $global;
echo $global; // "outer"
}
Prefer passing values as parameters — heavy global use makes code impossible to follow.
Common mistakes
1. Concatenating with +
Result is 0. Use . for strings.
2. Expecting $name to interpolate in single quotes
Single quotes print the literal text. Use double quotes or concatenation.
3. Comparing with ==
"0", "" and null compare equal in surprising combinations. Use ===.
4. Using a global variable inside a function
You get nothing. Pass it in as an argument.
5. Omitting declare(strict_types=1)
Arguments are coerced silently and the type bug surfaces far away from its cause.
6. Reading a missing array key
null plus a warning. Fall back with ??.
Summary
- Variables start with
$; assign before use, check withisset(). - Concatenate with
.; double quotes interpolate, single quotes do not. - Always compare with
===;"0"is falsy in PHP. - Add
declare(strict_types=1);to every new file. - Functions do not inherit global scope — pass values in.
Next: strings and arrays, the two types you touch most.