Variables and Data Types
PHP's core data types and how its loose, dynamic typing actually behaves.
2 min read
PHP is dynamically typed — a variable's type is determined by whatever value it currently holds, and can change if you reassign it.
The core scalar types
<?php
$name = "Amara"; // string
$age = 28; // int
$price = 19.99; // float
$isActive = true; // boolThese four — string, int, float, bool — cover most everyday values. Use var_dump() during development to see a variable's exact type and value:
<?php
var_dump($age);
// int(28)Arrays: PHP's do-everything collection type
<?php
$fruits = ["apple", "banana", "cherry"];
$user = ["name" => "Amara", "role" => "admin"];PHP has one array type that does the job of both a list and a dictionary: an indexed array ($fruits, keyed 0, 1, 2... automatically) and an associative array ($user, keyed by whatever string you choose). Both are the exact same underlying type — ["name" => "Amara"] is just an array with string keys instead of the default numeric ones.
null: the absence of a value
<?php
$middleName = null;
if ($middleName === null) {
echo "No middle name provided.";
}null represents "no value." A variable can also simply not exist yet — accessing an undefined variable emits a warning and evaluates to null, which is why explicitly initializing variables (even to null) is good practice rather than relying on that fallback behavior.
Checking a variable's type
<?php
$value = "42";
echo gettype($value); // "string"
var_dump(is_string($value)); // bool(true)
var_dump(is_numeric($value)); // bool(true) — looks numeric, even though it's a stringgettype() returns a type as a string; the is_* family (is_string, is_int, is_array, is_numeric, and more) returns a boolean, which is usually more useful in an if condition than comparing a string.
Constants: values that never change
<?php
define("MAX_LOGIN_ATTEMPTS", 5);
const APP_NAME = "DevLearnHub";
echo MAX_LOGIN_ATTEMPTS;define() and const both create a constant — a value that can't be reassigned after it's set. const is evaluated when the file is compiled (so it can only hold a fixed literal and is typically used at the top level or inside a class), while define() can be called conditionally at runtime. Constants don't use the $ prefix, and convention names them in SCREAMING_SNAKE_CASE.
Why "loose typing" catches people off guard
PHP will happily use a value as a different type when the context calls for it — a string like "5" behaves like the number 5 in arithmetic. The next lesson, on type conversion, covers exactly when that's convenient and when it quietly causes bugs.
Test what you just learned
4 quick questions. Get all of them right to unlock the next lesson.
You can take the quiz without an account — logging in just lets your result count toward your progress.