PHP ceil() function


The ceil() function in PHP rounds a number up to the nearest integer, regardless of its decimal part. Even if the decimal is less than 0.5, it will still round up to the next integer.

Syntax:

ceil(float $number): float
  • $number: The floating-point number you want to round up.
  • Return Value: Returns the smallest integer greater than or equal to the input number as a float.

Example 1: Rounding Up a Positive Decimal

<?php echo ceil(4.3); ?>

Output:

5

Explanation: 4.3 is rounded up to the nearest integer, which is 5.

Example 2: Rounding Up a Positive Decimal Close to the Next Integer

<?php echo ceil(7.9); ?>

Output:

8

Explanation: Even though 7.9 is close to 8, the function rounds it up to exactly 8.

Example 3: Rounding Up a Negative Decimal

<?php echo ceil(-3.4); ?>

Output:

-3

Explanation: -3.4 is rounded up towards zero, resulting in -3.

Example 4: Rounding Up an Integer

<?php echo ceil(5); ?>

Output:

5

Explanation: If the input is already an integer (like 5), the function returns the same integer without any changes.

Example 5: Rounding Up Zero

<?php echo ceil(0); ?>

Output:

0

Explanation: The number 0 stays as 0 because it is already the nearest integer.

Key Points:

  • The ceil() function always rounds up to the nearest integer.
  • It returns the result as a float, even though the value is an integer.
  • It works with both positive and negative numbers.
  • It is useful when you want to ensure that a number is rounded up, regardless of its fractional part.

For example, in scenarios where you need to calculate a minimum number of items or steps (like in pagination or batch processing), ceil() is particularly useful.