PHP Math Functions


PHP provides a rich set of mathematical functions and operators to perform calculations, manipulate numbers, and solve real-world problems. From simple arithmetic to advanced math operations, PHP has built-in tools that make working with numbers efficient and accurate.

Arithmetic Operators

PHP supports standard arithmetic operations:

<?php
$a = 15;
$b = 4;

echo "Addition: " . ($a + $b) . "<br>";        // 19
echo "Subtraction: " . ($a - $b) . "<br>";     // 11
echo "Multiplication: " . ($a * $b) . "<br>";  // 60
echo "Division: " . ($a / $b) . "<br>";        // 3.75
echo "Modulus: " . ($a % $b) . "<br>";         // 3
echo "Exponent: " . ($a ** $b) . "<br>";       // 50625
?>
  • +, -, *, /, %, ** are the main arithmetic operators.

  • % gives the remainder, and ** calculates powers.

  • Operator precedence matters; use parentheses to control the order.

Increment and Decrement Operators

PHP provides operators to increase or decrease numbers by 1:

<?php
$num = 10;
$num++; // Increment by 1
echo $num . "<br>"; // 11

$num--; // Decrement by 1
echo $num . "<br>"; // 10
?>
  • ++$num is pre-increment (changes before using the value).

  • $num++ is post-increment (changes after using the value).

  • Useful in loops and counters.

Assignment Operators with Math

You can combine arithmetic and assignment:

<?php
$num = 5;
$num += 10; // Equivalent to $num = $num + 10
echo $num . "<br>"; // 15

$num *= 2; // Equivalent to $num = $num * 2
echo $num . "<br>"; // 30
?>
  • +=, -=, *=, /=, %=, **= simplify calculations.

Built-in Math Functions

PHP has numerous built-in functions for common mathematical operations.

1. abs() – Absolute Value

<?php
echo abs(-50) . "<br>"; // 50
?>
  • Returns the positive value of a number.

2. round() – Round Numbers

<?php
echo round(3.14159, 2) . "<br>"; // 3.14
?>
  • Second argument specifies decimal precision.

3. ceil() – Round Up

<?php
echo ceil(4.2) . "<br>"; // 5
?>

4. floor() – Round Down

<?php
echo floor(4.8) . "<br>"; // 4
?>

5. pow() – Power

<?php
echo pow(2, 3) . "<br>"; // 8
?>
  • Equivalent to 2 ** 3.

6. sqrt() – Square Root

<?php
echo sqrt(16) . "<br>"; // 4
?>

7. max() and min() – Maximum and Minimum

<?php
echo max(2, 10, 5) . "<br>"; // 10
echo min(2, 10, 5) . "<br>"; // 2
?>

8. pi() – Mathematical Constant π

<?php
echo pi() . "<br>"; // 3.1415926535898
?>
  • Useful for geometry calculations like circumference or area.

Random Numbers

PHP can generate random numbers using rand() or mt_rand():

<?php
echo rand(1, 100) . "<br>";     // Random number between 1 and 100
echo mt_rand(1, 50) . "<br>";   // Faster and more secure
?>
  • Useful for games, simulations, or random selection.

Trigonometric Functions

PHP also supports trigonometric operations for advanced math:

<?php
$angle = pi() / 4; // 45 degrees in radians
echo sin($angle) . "<br>"; // Sine
echo cos($angle) . "<br>"; // Cosine
echo tan($angle) . "<br>"; // Tangent
?>
  • All trigonometric functions expect radians.

  • Use deg2rad() to convert degrees to radians.

<?php
$degrees = 45;
$radians = deg2rad($degrees);
echo sin($radians); // Converts to radians before calculating
?>

Number Formatting

PHP allows formatting numbers for display purposes using number_format():

<?php
$number = 1234.5678;
echo number_format($number, 2); // 1,234.57
echo number_format($number, 2, ".", ""); // 1234.57 without commas
?>
  • Helps display currency or reports in a readable format.

Common Mistakes and Tips

  • Division by zero produces warnings; always check the denominator:

<?php
$denominator = 0;
if ($denominator != 0) {
    echo 10 / $denominator;
} else {
    echo "Cannot divide by zero!";
}
?>
  • Truncating floats using (int) is different from rounding; use round() if needed.

  • Random number functions may produce the same number repeatedly if seeded improperly; use mt_srand() for better randomness.

Summary of the Tutorial

  • PHP supports arithmetic operators: +, -, *, /, %, **.

  • Increment (++) and decrement (--) operators simplify counting.

  • Assignment operators with math (+=, -=, *=) combine operations efficiently.

  • Built-in math functions: abs(), round(), ceil(), floor(), pow(), sqrt(), max(), min(), pi().

  • Random numbers can be generated using rand() or mt_rand().

  • Trigonometric functions (sin(), cos(), tan()) work in radians.

  • number_format() formats numbers for display.

  • Avoid dividing by zero and choose the right rounding method.

Mastering PHP math functions and operators is essential for calculations, statistics, geometry, game development, and data processing.


Practice Questions

  1. Create a PHP script that adds two numbers $a = 15 and $b = 7 and prints the result. Include a comment explaining addition.

  2. Declare two variables $x = 10 and $y = 3, subtract $y from $x, and print the result. Include a comment explaining subtraction.

  3. Write a PHP script that multiplies $a = 5 and $b = 6 and prints the result. Include a comment explaining multiplication.

  4. Create a PHP script that divides $num1 = 20 by $num2 = 4 and prints the result. Include a comment and check for division by zero.

  5. Write a PHP script that calculates the remainder of $num1 = 17 divided by $num2 = 5 using the modulus operator % and prints it. Include a comment.

  6. Create a PHP file that calculates the power of a number, $base = 2 and $exponent = 3, using both ** and pow(). Include a comment explaining each method.

  7. Write a PHP script that rounds a float $num = 3.14159 to 2 decimal places using round(), rounds up using ceil(), and rounds down using floor(). Include comments explaining each function.

  8. Create a PHP script that generates a random number between 1 and 100 using rand() and prints it. Include a comment explaining random number generation.

  9. Write a PHP file that calculates the square root of $num = 25 using sqrt() and prints it. Include a comment.

  10. Create a PHP script that formats the number $number = 1234.5678 to 2 decimal places using number_format() and prints it. Include a comment explaining its use for display.


Go Back Top