Types And Values
Every value in PHP has a type. The type describes what kind of value PHP is holding and influences which operations, comparisons, function calls, and output conversions make sense.
The characters 25 can represent different values depending on the source code: 25 is an integer, '25' is a string containing two characters, and 25.0 is a floating-point value. They may look similar when printed, but they are not interchangeable contracts.
Inspect Type And Value Together
Use var_dump() when you need to see both type and value:
<?php
$productName = 'Notebook';
$priceCents = 1299;
$inStock = true;
$discountCents = null;
var_dump($productName);
var_dump($priceCents);
var_dump($inStock);
var_dump($discountCents);
Output:
string(8) "Notebook"
int(1299)
bool(true)
NULL
For a string, var_dump() includes its byte length and content. For integers and booleans it shows the type name and value. NULL indicates the one value of PHP's null type.
var_dump() can inspect several values in one call:
<?php
var_dump('25', 25, 25.0, true, null);
This is useful while learning or diagnosing a boundary. Remove uncontrolled dumps from normal application output: they can corrupt JSON or HTML, reveal data, and make a command's output unstable.
Ask For A Type Name
get_debug_type() returns a useful type name as a string:
<?php
$rating = 4.5;
echo get_debug_type($rating), PHP_EOL;
Output:
float
Use var_dump() when the value and detailed structure matter. Use get_debug_type() when a diagnostic message needs only the type name. PHP also has specific checks such as is_string(), is_int(), is_float(), is_bool(), is_null(), and is_array() for code that needs to test a type deliberately.
Recognise The Four Scalar Types
PHP's scalar types hold single values:
bool:trueorfalse;int: a whole number;float: a floating-point number;string: a sequence of bytes representing text or other data.
<?php
$isPublished = false;
$quantity = 3;
$rating = 4.5;
$title = 'PHP Basics';
var_dump($isPublished, $quantity, $rating, $title);
Output:
bool(false)
int(3)
float(4.5)
string(10) "PHP Basics"
A variable does not permanently own one scalar type merely because of its name. The assigned value determines its current type:
<?php
$value = '10';
var_dump($value);
$value = 10;
var_dump($value);
The first dump reports string; the second reports int. This flexibility does not mean changing one variable between unrelated meanings is good design. Stable data contracts make programs easier to understand and analyse.
Use Integers For Exact Whole Units
An integer stores a whole number:
<?php
$itemCount = 4;
$priceCents = 1299;
$temperatureOffset = -2;
var_dump($itemCount, $priceCents, $temperatureOffset);
Money examples often use integer minor units such as cents or pence because whole-unit arithmetic is exact. The value 1299 paired with a name such as $priceCents means 12.99 in a two-decimal currency without asking a binary floating-point value to represent that decimal exactly.
Integer size depends on the PHP build and platform. PHP_INT_SIZE, PHP_INT_MAX, and PHP_INT_MIN describe the current runtime. Application identifiers may exceed a database or external system's integer range, so do not convert every digit-only identifier into an integer automatically. A postal code, phone number, account reference, or SKU can be text even when it contains only digits.
Understand Floating-Point Limits
A float represents numbers with a fractional component or values outside the integer range:
<?php
$rating = 4.5;
$ratio = 2 / 3;
var_dump($rating, $ratio);
Floating-point values use finite binary representations. Many decimal fractions cannot be represented exactly:
<?php
var_dump(0.1 + 0.2);
The result is close to 0.3, but its dump can reveal additional digits. Do not compare calculated floats for exact equality or use binary floats for exact currency totals. Use integer minor units, a decimal library, or another representation designed for the domain.
Formatting a float to two decimal places changes its displayed text, not the underlying mathematical accuracy. Representation and value remain separate concerns.
Treat Booleans As Two Explicit Values
A boolean is either true or false:
<?php
$isInStock = true;
$isDiscontinued = false;
var_dump($isInStock, $isDiscontinued);
Plain echo is a poor boolean inspector:
<?php
echo true, PHP_EOL;
echo false, PHP_EOL;
true is converted to the string "1", while false becomes an empty string. The second value can therefore look like missing output. Use var_dump() during diagnosis or convert deliberately to labels such as yes and no when producing user-facing output.
PHP can interpret other values in a logical context. Empty strings, zero, and some other values can behave as false. Those truthiness rules are covered with control flow. At data boundaries, prefer a real boolean over a collection of undocumented truthy and falsy substitutes.
Use null For Intentional Absence
null represents an intentionally absent value:
<?php
$discountCents = null;
var_dump($discountCents);
null is not the same as 0, false, or an empty string:
<?php
var_dump(null, 0, false, '');
Each value has a different type and can carry a different domain meaning. A discount of 0 might mean the product has a known zero discount; null might mean no discount decision has been recorded. Define that meaning instead of using null as a vague replacement for every invalid or unknown state.
Echoing null produces an empty string, so use a dump or explicit label when checking it.
Arrays Hold Multiple Values
An array can hold a list or key-value structure:
<?php
$tags = ['php', 'beginner'];
$product = [
'name' => 'Notebook',
'quantity' => 3,
'rating' => 4.5,
'in_stock' => true,
'discount_cents' => null,
];
var_dump($tags);
var_dump($product);
One array can contain values of different types. That flexibility makes the keys and expected value types part of an informal contract. Later lessons teach array access, iteration, transformation, and validation.
Do not pass an array directly to echo; PHP cannot turn a complete array into useful ordinary text and reports a warning. Inspect it with var_dump() or format its elements deliberately.
Know That Other Types Exist
PHP also supports objects, resources, callables, and additional declaration-only or control-flow types. You will meet them when the course reaches objects, files, databases, functions, and type declarations.
A resource is a handle to an external facility such as an open stream. An object is an instance of a class. Their behavior cannot be reduced to the scalar rules in this lesson, but get_debug_type() and var_dump() remain useful first inspection tools.
The goal now is not to memorise every PHP type. It is to stop assuming that printed appearance tells you the value's contract.
Output Can Hide Type Differences
These values print similarly:
<?php
echo '25', PHP_EOL;
echo 25, PHP_EOL;
echo 25.0, PHP_EOL;
Output:
25
25
25
echo uses a string context, so PHP converts printable scalar values for output. The original values remain a string, integer, and float. Inspect before output when that distinction matters:
<?php
var_dump('25', 25, 25.0);
Automatic conversion in one context is not proof that the data is valid for every context. A numeric-looking string can be printable while still needing validation before it becomes a quantity.
External Input Usually Starts As Text
Command-line arguments, query parameters, form fields, environment variables, CSV cells, and many database-driver results can arrive as strings:
<?php
$quantityInput = '10';
var_dump($quantityInput);
Quotes are not visible in a form field, but the PHP value can still be string(2) "10". The program must decide whether 10 is an allowed integer quantity, a textual identifier, or invalid input.
Never infer validation from appearance alone. These inputs need different decisions:
10
010
10.5
10 items
-3
(empty string)
The correct rule belongs to the domain. A positive quantity may allow only integers from 1 upward. A code may need to preserve leading zeroes and remain a string.
Validate Before Converting
A cast forces a conversion:
<?php
$quantity = (int) '12';
var_dump($quantity);
This produces int(12), but casting is not validation. For example, blindly casting malformed input can discard information and produce a plausible value.
Use a validator when the string must satisfy an integer contract:
<?php
$quantityInput = '12';
$quantity = filter_var(
$quantityInput,
FILTER_VALIDATE_INT,
['options' => ['min_range' => 1]],
);
var_dump($quantity);
A valid input produces an integer. An invalid input produces false, which must be checked before the value is used. Because false is also a possible result value in many PHP APIs, read each function's documented return contract instead of guessing.
Do not cast first and validate the converted result. Validation should examine the original boundary value so malformed characters and unsupported forms remain visible.
Type Juggling Is Context, Not A Data Contract
PHP can interpret values as another type in numeric, string, logical, comparison, and function contexts. This behavior is called type juggling.
A variable's value does not necessarily change merely because an operation interprets it in another context. More importantly, successful coercion does not establish that the original input met the application's rules.
Prefer this workflow:
- inspect or know the boundary type;
- validate the allowed representation and range;
- convert to the application's intended type;
- keep that internal type consistent;
- format it deliberately at the output boundary.
Strict type declarations and comparison operators receive dedicated lessons later. They reinforce this same principle: make contracts explicit instead of depending on surprising conversion.
Common Type Mistakes
| Symptom | Likely cause |
|---|---|
| Values look identical when echoed | String conversion hid their original types |
false seems to print nothing |
Boolean false converts to an empty string |
| Missing value looks like empty text | null was echoed instead of inspected |
| Array produces a warning when printed | Complete array was passed to string output |
| Decimal calculation has extra digits | Binary floating-point representation is approximate |
| Invalid quantity becomes a number | Input was cast instead of validated |
| Leading zeroes disappear | Textual identifier was converted to an integer |
| Variable changes type unexpectedly | A new value of another type was reassigned |
What You Should Be Able To Do
After this lesson, you should be able to recognise strings, integers, floats, booleans, null, and arrays; inspect values with var_dump() and get_debug_type(); explain why output can hide type differences; distinguish absence from zero or false; avoid float assumptions for exact money; and validate external text before converting it to an application type.
Official references include PHP's type system, type juggling, var_dump(), and filter_var().
Practice
Practice: Inspect A Product Snapshot
- product name
'Notebook' - price in cents
1299 - rating
4.5 - stock status
true - discount in cents
null - tags
['paper', 'office']
Requirements
- use descriptive variable names
- call
var_dump()once with all six variables - print one additional line containing the type names returned by
get_debug_type()for the price, discount, and tags - do not convert any value merely to make the dump look different
- lint and execute the file
Afterward, identify the exact type of every variable. Explain why null is more precise than an empty string when the intended meaning is "no discount has been assigned," and why price uses integer cents rather than a float.
Show solution
<?php
$productName = 'Notebook';
$priceCents = 1299;
$rating = 4.5;
$isInStock = true;
$discountCents = null;
$tags = ['paper', 'office'];
var_dump(
$productName,
$priceCents,
$rating,
$isInStock,
$discountCents,
$tags,
);
echo 'Selected types: ',
get_debug_type($priceCents), ', ',
get_debug_type($discountCents), ', ',
get_debug_type($tags),
PHP_EOL;
The values have types string, int, float, bool, null, and array in declaration order. The final line is:
Selected types: int, null, array
null states that no discount value has been assigned. An empty string would instead be a present string whose content happens to be empty, which is a different state.
The price uses integer cents so the stored unit is exact. A binary floating-point value such as 12.99 is not an appropriate assumption for exact currency arithmetic.
Practice: Predict Display And Type
<?php
$textNumber = '25';
$wholeNumber = 25;
$decimalNumber = 25.0;
$enabled = true;
$disabled = false;
$missing = null;
echo "echo values:\n";
echo $textNumber, PHP_EOL;
echo $wholeNumber, PHP_EOL;
echo $decimalNumber, PHP_EOL;
echo $enabled, PHP_EOL;
echo $disabled, PHP_EOL;
echo $missing, PHP_EOL;
echo "dump values:\n";
var_dump(
$textNumber,
$wholeNumber,
$decimalNumber,
$enabled,
$disabled,
$missing,
);
Verification
- record the exact visible output before running the file
- identify which different types look the same through
echo - identify which values produce an apparently blank line
- lint and execute the script
- compare your prediction with the actual result
Afterward, explain why echo is an output tool rather than a reliable type inspector.
Show solution
echo values:
25
25
25
1
dump values:
string(2) "25"
int(25)
float(25)
bool(true)
bool(false)
NULL
The exact float dump format can include .0 behavior according to runtime configuration such as serialize_precision, but its type remains float.
The string '25', integer 25, and float 25.0 all display as 25 through echo. Boolean true displays as 1. Boolean false and null convert to empty strings, so the explicit PHP_EOL calls create two apparently blank lines.
var_dump() preserves the distinctions that string output hides. It reports the string length, integer type, float type, boolean values, and NULL explicitly. Use echo to produce a chosen output representation; use an inspection tool when the stored type is the question.
Practice: Validate Before Converting
$validQuantityInput = '12';
$malformedQuantityInput = '12 items';
$negativeQuantityInput = '-3';
$skuInput = '00125';
Task
- validate each quantity input with
filter_var()andFILTER_VALIDATE_INT - require a minimum integer value of
1 - also cast
$malformedQuantityInputdirectly tointfor comparison - leave
$skuInputas a string - use
var_dump()to inspect all original inputs and results
Do not add conditions yet; the goal is to inspect each return value and type.
After running the file, explain:
- why the valid quantity becomes an integer
- why the malformed and negative values return
false - why the direct cast is dangerous evidence of validation
- why the SKU must keep its leading zeroes and remain a string
Show solution
<?php
$validQuantityInput = '12';
$malformedQuantityInput = '12 items';
$negativeQuantityInput = '-3';
$skuInput = '00125';
$validationOptions = [
'options' => ['min_range' => 1],
];
$validQuantity = filter_var(
$validQuantityInput,
FILTER_VALIDATE_INT,
$validationOptions,
);
$malformedQuantity = filter_var(
$malformedQuantityInput,
FILTER_VALIDATE_INT,
$validationOptions,
);
$negativeQuantity = filter_var(
$negativeQuantityInput,
FILTER_VALIDATE_INT,
$validationOptions,
);
$blindlyCastQuantity = (int) $malformedQuantityInput;
var_dump(
$validQuantityInput,
$validQuantity,
$malformedQuantityInput,
$malformedQuantity,
$negativeQuantityInput,
$negativeQuantity,
$blindlyCastQuantity,
$skuInput,
);
The valid string produces int(12). The malformed value contains unsupported text, and -3 is below the configured minimum, so both validation calls produce bool(false).
The direct cast can produce int(12) from '12 items', discarding the invalid suffix. That result looks usable but does not prove the original input satisfied the quantity contract.
$skuInput remains string(5) "00125". Converting it to an integer would remove leading zeroes and change an identifier into a numeric quantity, even though no arithmetic is required.