PHP handles numbers gracefully. You've got two main types: integers (whole numbers) and floats (decimal numbers). PHP automatically converts between them as needed, but knowing the difference helps you avoid surprises.
Integers and Floats
An integer is a whole number without a decimal point. A float has a decimal point or uses scientific notation. PHP stores them differently internally, but you'll barely notice unless you're doing very precise calculations.
<?php
$age = 25; // integer
$price = 19.99; // float
$large = 2.5e3; // float โ 2500
$small = 3.5e-3; // float โ 0.0035
var_dump($age);
var_dump($price);
?>
Try it Yourself โ
Arithmetic Operators
PHP supports all the standard math operations. Nothing surprising here โ addition, subtraction, multiplication, division, modulus, and exponentiation.
<?php
$a = 10;
$b = 3;
echo $a + $b; // 13
echo $a - $b; // 7
echo $a * $b; // 30
echo $a / $b; // 3.3333...
echo $a % $b; // 1 (modulus โ remainder of division)
echo $a ** $b; // 1000 (10 to the power of 3)
?>
Checking Types with is_int() and is_float()
PHP provides boolean helper functions to check if a value is a specific type. is_int() returns true if the value is an integer, is_float() for floats. These are especially useful for validating user input.
<?php
$x = 42;
$y = 3.14;
var_dump(is_int($x)); // true
var_dump(is_int($y)); // false
var_dump(is_float($x)); // false
var_dump(is_float($y)); // true
// Also: is_numeric() checks if a value is a number or numeric string
var_dump(is_numeric("42")); // true
var_dump(is_numeric("abc")); // false
?>
Formatting Numbers
When you display numbers to users, you usually want to format them nicely. number_format() is your friend. It adds thousands separators and controls decimal places.
<?php
$number = 1234567.89;
echo number_format($number); // 1,234,568
echo number_format($number, 2); // 1,234,567.89
echo number_format($number, 2, ",", "."); // 1.234.567,89 (European style)
?>