Skip to content
Home Tutorials Roadmaps Courses
Log in Join free
Tutorials PHP Math Functions
PHP Intermediate FREE

Math Functions

Lesson 2 of 17 Intermediate Interactive

PHP provides many built-in math functions for working with numbers. These functions help with calculations, rounding, and formatting.

Essential Math Functions

  • abs() — Absolute value (positive number)
  • round() — Round to nearest integer
  • ceil() — Round up to next integer
  • floor() — Round down to previous integer
  • rand() — Generate a random integer
  • min() — Get the smallest value
  • max() — Get the largest value
  • number_format() — Format a number with commas and decimals

PHP Math Constants

  • M_PI — Value of Pi (3.14159...)
  • M_E — Euler's number (2.71828...)
  • PHP_INT_MAX — Largest integer supported

Syntax

PHP
<?php
abs(-5);         // 5

round(4.6);      // 5

round(4.3);      // 4

ceil(4.2);       // 5

floor(4.9);      // 4

rand(1, 10);     // Random number 1-10

min(3, 7, 1);    // 1

max(3, 7, 1);    // 7

number_format(1234567.891, 2, ".", ","); // "1,234,567.89"

echo M_PI;        // 3.1415926535898

?>
Math Operations in PHP
PHP
<?php
$a = 10;
$b = 3;

echo "Add: " . ($a + $b) . "
";
echo "Subtract: " . ($a - $b) . "
";
echo "Multiply: " . ($a * $b) . "
";
echo "Divide: " . ($a / $b) . "
";
echo "Modulus: " . ($a % $b) . "
";
echo "Power: " . ($a ** $b) . "
";

echo "Round: " . round(3.7) . "
";
echo "Ceil: " . ceil(3.2) . "
";
echo "Floor: " . floor(3.8) . "
";
echo "Max: " . max(1, 5, 3) . "
";
echo "Min: " . min(1, 5, 3) . "
";
echo "Rand: " . rand(1, 10) . "
";
?>

Practice

1
Exercise

Calculate the area of a rectangle with width 7.5 and height 12.3, rounded to 2 decimal places.

Answer
<?php
$width = 7.5;
$height = 12.3;
$area = $width * $height;
echo "Area: " . number_format($area, 2);
?>
2
Exercise

Generate a random number between 1 and 100 and display whether it is even or odd.

Answer
<?php
$number = rand(1, 100);
echo "Number: $number<br>";
echo ($number % 2 === 0) ? "Even" : "Odd";
?>

Quick Quiz

1

What does ceil(4.2) return?

ceil() always rounds up to the next whole number, so ceil(4.2) returns 5.

2

How do you format 1000000 with commas?

number_format() adds thousands separators and formatting to a number.

3

Which constant returns the value of Pi?

M_PI is the built-in PHP constant for Pi.

Interview Questions

Use ceil() when you always need to round up — for example, calculating the number of pages needed (e.g., 31 items / 10 per page = ceil(3.1) = 4 pages). Use round() when you want the nearest integer — for example, rounding prices or averages.

rand() is not cryptographically secure. It uses a predictable algorithm and its output can be guessed. For security-sensitive operations like generating tokens or passwords, use random_int() (PHP 7+) which uses a cryptographically secure random number generator.