A PHP variable stores a value and begins with $. PHP determines the variable type from the assigned value, so the same variable can technically receive another type later.
Useful PHP code still treats types deliberately. A price, user name, enabled flag, and missing result have different operations and different failure modes.
<?php
$course = 'PHP';
$lessons = 12;
$progress = 0.25;
$isActive = true;
$nextLesson = null;
var_dump($course, $lessons, $progress, $isActive, $nextLesson);
string(3) "PHP"
int(12)
float(0.25)
bool(true)
NULL
var_dump() shows both the type and value, which is useful when input does not behave as expected.
| Type | Example | Typical use |
|---|---|---|
| string | 'PHP' | Text |
| int | 42 | Whole numbers and identifiers |
| float | 19.95 | Measurements and decimal calculations |
| bool | true | Two-state decisions |
| null | null | No value is present |
| array | ['php', 'sql'] | Ordered or keyed collections |
| object | new Course() | State and behavior defined by a class |
| resource | fopen(...) | Handle to an external resource |
PHP may coerce values in arithmetic, comparison, or a non-strict function call. That convenience can hide bad input, especially with numeric strings and loose comparison.
Convert at the boundary when the expected type is known. Validate first when a failed conversion must be distinguished from a legitimate zero.
<?php
$rawQuantity = '12';
$quantity = filter_var($rawQuantity, FILTER_VALIDATE_INT);
if ($quantity === false) {
echo 'Quantity must be a whole number.';
} else {
echo 'Items: ' . $quantity;
}
Items: 12
The strict === false check keeps a valid integer 0 separate from failed validation.
isset($value) is false when a variable is undefined or null. array_key_exists() is useful when an array key may intentionally contain null. The null coalescing operator provides a default for undefined or null values.
| Question | Tool |
|---|---|
| Is this variable defined and non-null? | isset($value) |
| Does this array key exist even if its value is null? | array_key_exists('key', $array) |
| Use a default for missing or null input | $value ?? 'default' |
| Inspect the exact runtime type | get_debug_type($value) or var_dump($value) |
0 of 2 checked
Try this next
0 of 2 completed
Explore 500+ free tutorials across 20+ languages and frameworks.