floor()
Today, we will discuss the floor() function in PHP. This function is used to round a number down to the nearest integer.
The floor() function in PHP rounds a number down to the nearest integer — that is, it returns the largest integer that is less than or equal to the value you give it. "Down" here always means toward negative infinity, which is the detail most people get wrong. This page covers the syntax, how floor() behaves with positive and negative numbers, the type it returns, and when to reach for it instead of ceil(), round(), or intdiv().
Syntax
floor(int|float $num): float$num— the value to round down. It can be anintor afloat.- Return value — the result is always returned as a
float, even when it represents a whole number. Sofloor(7)gives7.0, not7. If you need an actual integer, cast the result:(int) floor($num).
A basic example
We assign a float to $number, pass it to floor(), and the function returns 3 — the largest integer that is not greater than 3.14. Anything after the decimal point is simply discarded for positive numbers.
How floor() handles negative numbers
This is the part that trips people up. floor() rounds toward negative infinity, so a negative value rounds away from zero, not toward it.
<?php
echo floor(4.7); // 4
echo "\n";
echo floor(-4.7); // -5 (down means more negative)
echo "\n";
echo floor(-4.1); // -5
echo "\n";
echo floor(8); // 8 (already an integer)
?>For -4.7, the integers below it are -5, -6, ...; the largest of those is -5. If you wanted -4 (rounding toward zero), you would use ceil() or a cast like (int) -4.7 instead.
floor() vs. ceil() vs. round()
These three functions all return whole numbers but differ in direction:
| Function | Direction | floor(2.5) / ceil(2.5) / round(2.5) |
|---|---|---|
floor() | Always down (toward −∞) | 2.0 |
ceil() | Always up (toward +∞) | 3.0 |
round() | To the nearest, halves up by default | 3.0 |
<?php
echo floor(2.5); // 2
echo "\n";
echo ceil(2.5); // 3
echo "\n";
echo round(2.5); // 3
?>When would I use floor()?
floor() shows up whenever you need a whole count that must never overshoot:
- Pagination — number of full pages:
floor($totalItems / $perPage). - Time/units — whole hours from minutes:
floor($minutes / 60). - Money/quantities — how many whole items fit in a budget:
floor($budget / $price).
<?php
$totalItems = 47;
$perPage = 10;
$fullPages = floor($totalItems / $perPage);
echo "Full pages: " . $fullPages; // Full pages: 4
?>Note: For integer division you can also use
intdiv(), which returns a trueintand is clearer when both operands are integers. Usefloor()when floats are involved.
Conclusion
floor() always rounds down toward negative infinity and returns a float. Keep in mind that negative numbers round away from zero, and cast to (int) if you need an integer type. For the opposite direction use ceil(), for nearest-value rounding use round(), and for formatting numbers with thousands separators see number_format().