PHP provides a comprehensive suite of mathematical functions for rounding, root calculations, min/max evaluation, exponentiation, and secure random number generation.
| Function | Purpose | Example |
|---|---|---|
pi() |
Returns approximation of PI ($\pi$) | pi() $pprox 3.14159265...$ |
min(), max() |
Finds lowest or highest value in set | min(4, 9, 2) $ |
| ightarrow 2$ | ||
abs() |
Returns absolute positive value | abs(-15.5) $ |
| ightarrow 15.5$ | ||
sqrt() |
Calculates square root | sqrt(64) $ |
| ightarrow 8.0$ | ||
pow() |
Raises base to exponent power | pow(2, 8) $ |
| ightarrow 256$ | ||
round() |
Rounds float to nearest integer/decimal | round(3.567, 2) $ |
| ightarrow 3.57$ | ||
ceil(), floor() |
Rounds strictly up or down | ceil(4.1) $ |
ightarrow 5$, floor(4.9) $ |
||
| ightarrow 4$ | ||
random_int() |
Cryptographically secure random integer | random_int(100000, 999999) |
flowchart TD
A["Numeric Calculation"] --> B{"Choose Operator / Function"}
B -- Exponentiation --> C["$base ** $exp or pow($base, $exp)"]
B -- Rounding Strategy --> D["ceil() / floor() / round()"]
B -- Range Clamping --> E["min(max($val, $minBound), $maxBound)"]
B -- Secure Random Token --> F["random_int($min, $max)"]
<?php
declare(strict_types=1);
// 1. Clamping Values within Bounds (Min & Max)
$userAgeInput = 145;
$clampedAge = min(max($userAgeInput, 1), 120); // Clamped between 1 and 120
// 2. Rounding Strategies
$price = 19.846;
$roundedPrice = round($price, 2); // 19.85
$ceilingPrice = ceil($price); // 20.0
$floorPrice = floor($price); // 19.0
// 3. Cryptographically Secure OTP / Random Generation
$securityOTP = random_int(100000, 999999);
// 4. Circle Area Calculation
$radius = 7.5;
$circleArea = pi() * pow($radius, 2);
echo "Clamped Age: " . $clampedAge . "
";
echo "Rounded Price: $" . $roundedPrice . "
";
echo "Generated 6-Digit OTP: " . $securityOTP . "
";
echo "Circle Area (r=7.5): " . round($circleArea, 4) . " sq units
";
random_int() over rand() or mt_rand(): random_int() produces cryptographically secure pseudorandom numbers suitable for security tokens and OTP passwords.**: Use $x ** 2 instead of pow($x, 2) for concise code.round($val, $precision).Write a function generateCouponCode(): string that generates a random 8-digit numeric verification code using random_int(10000000, 99999999)!
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.