HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

PHP Math Functions

PHP has a set of built-in math functions that allow you to perform mathematical tasks on numbers. Whether you need to generate a random number or find the square root of a value, PHP makes it simple.


1. The pi() Function

The pi() function returns the value of PI.

<?php
    echo pi(); // Output: 3.1415926535898
?>

2. min() and max()

These functions find the lowest or highest value in a list of arguments.

<?php
    echo min(0, 150, 30, 20, -8, -200);  // Output: -200
    echo max(0, 150, 30, 20, -8, -200);  // Output: 150
?>

3. abs() - Absolute Value

Returns the absolute (positive) value of a number.

<?php
    echo abs(-6.7); // Output: 6.7
?>

4. sqrt() - Square Root

Returns the square root of a number.

<?php
    echo sqrt(64); // Output: 8
?>

5. round() - Rounding

The round() function rounds a floating-point number to its nearest integer.

<?php
    echo round(0.60);  // Output: 1
    echo round(0.49);  // Output: 0
?>

6. rand() - Random Numbers

The rand() function generates a random number. You can specify the range of the random number too.

<?php
    echo rand(); // Returns a random number
    echo rand(10, 100); // Returns a random number between 10 and 100
?>
Cryptography Note: The rand() function is not cryptographically secure. For security purposes (like passwords), use random_int() instead.
Pro Tip: Use ceil() to always round up to the nearest integer, and floor() to always round down.

Quick Reference Table

Function Description
pi()Returns 3.14...
min() / max()Returns the lower / higher value.
abs()Returns the positive value.
sqrt()Returns the square root.
round()Rounds to the nearest whole number.
rand()Generates a random number.