PHP Numbers
PHP represents numeric values with three main types: integers, floats, and numeric strings, each with its own behavior and helper functions.
Numeric Types in PHP
Unlike some languages that force you to declare a type up front, PHP infers the numeric type from the value you assign. A whole number becomes an integer, a value with a decimal point becomes a float, and text that happens to contain digits is treated as a numeric string until you use it in a calculation. Understanding which type you are holding matters because it affects comparisons, division, and the results returned by built-in functions.
- Integer: a whole number with no fractional part, such as 42 or -7.
- Float: a number that carries a decimal point or exponent, such as 3.14 or 2.5e3.
- Numeric string: a string whose contents look like a number, such as "100" read from a form or file.
Detecting numeric types
<?php
$whole = 42;
$decimal = 3.14;
$fromForm = "250";
var_dump(is_int($whole)); // bool(true)
var_dump(is_float($decimal)); // bool(true)
var_dump(is_numeric($fromForm)); // bool(true)
var_dump(is_int($fromForm)); // bool(false) - still a string
?>Integer Limits and Overflow
Integers in PHP are bounded by the platform, and the constant PHP_INT_MAX tells you the largest value your system can hold as an integer (commonly 9223372036854775807 on 64-bit builds). When a calculation exceeds that limit, PHP does not crash or wrap around; instead it quietly promotes the result to a float, which trades exact precision for a much larger range.
Watching an integer become a float
<?php
$max = PHP_INT_MAX;
echo $max, "\n"; // 9223372036854775807
var_dump(is_int($max)); // bool(true)
$overflow = $max + 1;
var_dump(is_float($overflow)); // bool(true)
?>Converting and Validating Numbers
Because form input and file contents arrive as strings, you often need to convert them before doing arithmetic. Casting with (int) or (float) forces a type, while functions like intval() and floatval() do the same job and accept extra options such as a number base. Always validate first when the data comes from users, since a stray letter can turn a calculation into an unexpected result.
Exercise: PHP Numbers
What is the result type of 10 / 3 in PHP?