Variables and Data Types
PHP is loosely typed — a variable's type is determined automatically based on the value it holds, and can change as the script runs.
Core Data Types
Unlike statically typed languages, you don't declare a type when creating a PHP variable — it's inferred from the assigned value, and can be checked at runtime with functions like gettype().
$name = "Sizwe"; // string
$age = 28; // integer
$price = 19.99; // float
$isEnrolled = true; // boolean
$student = null; // null
echo gettype($age); // outputs: integer
Type Juggling
PHP automatically converts between types in many operations, a behaviour called type juggling. This is convenient, but can produce surprising results if you aren't paying attention to it.
$result = "5" + 3; // 8 — the string "5" is converted to an integer
$result2 = "5" . 3; // "53" — the . operator forces string concatenation
Common Mistakes
- Confusing the string concatenation operator (.) with the addition operator (+), which produces very different results.
- Relying on loose comparison (==) when strict comparison (===) is what's actually needed, especially when comparing against 0 or an empty string.
- Assuming a variable's type will never change — PHP happily lets a variable hold a string at one point and an integer later.
- Forgetting that null is a distinct type from an empty string or 0, even though all three can behave as "falsy" in conditions.
Professional Tip
Use === (strict comparison) instead of == whenever you need to compare both value and type. This avoids common bugs where PHP's automatic type juggling makes two very different values seem equal.
Your Turn
Write a script that declares one variable of each core type, prints each one's type using gettype(), and demonstrates the difference between == and === on one comparison.
Mini Quiz
What does the . operator do when used between a string and a number in PHP?