PHP Basics · Chapter 20 · Math Functions

PHP Math Functions
Complete Guide in Hindi

PHP के सभी Math Functions की पूरी जानकारी — abs, ceil, floor, round, pow, sqrt, rand, number_format, fmod, intdiv, PHP Constants। Real examples के साथ।

🔢 Basic Math ⬆️ Rounding 🎲 Random 💰 Formatting 📐 Advanced
abs()Absolute value
round()Round करना
rand()Random number
M_PIPi constant = 3.14159...

📋 इस Article में क्या-क्या है

  1. Basic Math Functions
  2. Rounding — ceil, floor, round
  3. Power & Roots — pow, sqrt
  4. Random Numbers — rand, mt_rand
  5. Number Formatting
  6. Math Constants
  7. Integer Math — intdiv, fmod
  8. Min, Max, Range
  9. Trigonometric Functions
  10. Real World Examples
1
Basic Math Functions
BASIC MATH — abs, sign, intdiv
<?php
// abs() — Absolute value (negative → positive)
echo abs(-42); // 42
echo abs(42); // 42
echo abs(-3.14); // 3.14

// Real use — temperature difference
$diff = abs(37.5 - 36.9); // 0.6 degrees

// intdiv() — Integer Division (PHP 7+)
echo intdiv(7, 2); // 3 (quotient only)
echo intdiv(10, 3); // 3

// fmod() — Float Modulus (remainder)
echo fmod(10.5, 3.2); // 0.9
echo 10 % 3; // 1 (integer modulus)

// is_numeric() — check
var_dump(is_numeric("42")); // true
var_dump(is_numeric("3.14")); // true
var_dump(is_numeric("abc")); // false

// is_int, is_float checks
var_dump(is_int(42)); // true
var_dump(is_float(3.14)); // true
?>

2
Rounding — ceil(), floor(), round()
⬆️⬇️
rnd

ceil() / floor() / round()

ceil() — ऊपर round (ceiling)। floor() — नीचे round (floor)। round() — nearest integer/decimal। E-commerce, billing में ज़रूरी।

ceil = ऊपर floor = नीचे round = nearest
Valueceil()floor()round()
4.1544
4.5545
4.9545
-4.5-4-5-5
ROUNDING — REAL WORLD
<?php
// ceil — ऊपर (पेज count, shipping)
echo ceil(4.1); // 5
echo ceil(4.0); // 4
echo ceil(-4.5); // -4

// Pagination — total pages
$total = 47;
$perPage = 10;
echo ceil($total / $perPage); // 5 pages

// floor — नीचे (age, discount tiers)
echo floor(4.9); // 4
echo floor(-4.1); // -5

// Age from seconds
$ageSeconds = time() - strtotime("2000-06-15");
echo floor($ageSeconds / (365.25 * 86400)); // 24 years

// round — nearest (billing, GST)
echo round(4.4); // 4
echo round(4.5); // 5
echo round(3.14159, 2); // 3.14 (2 decimals)
echo round(1299.505, 2); // 1299.51

// GST calculation — round to 2 decimals
$price = 1000;
$gst = round($price * 0.18, 2); // 180.00
$total = round($price + $gst, 2); // 1180.00
?>
💡 Float precision: 0.1 + 0.2 !== 0.3 in PHP (floating point)। Always round() use करो financial calculations में — या bcmath extension use करो high-precision के लिए।

3
Power और Roots — pow(), sqrt(), log()
POWER & ROOTS — EXAMPLES
<?php
// pow() — power (घात)
echo pow(2, 10); // 1024 (2^10)
echo pow(3, 3); // 27
echo 2 ** 10; // 1024 (** operator — same)

// sqrt() — Square root
echo sqrt(25); // 5
echo sqrt(2); // 1.4142135...

// Compound Interest — A = P(1+r/n)^(nt)
$P = 10000; // Principal
$r = 0.08; // 8% annual rate
$n = 12; // Monthly compounding
$t = 5; // 5 years
$A = round($P * pow(1 + $r/$n, $n*$t), 2);
echo "₹$P → ₹$A after $t years"; // ₹10000 → ₹14898.46

// log() — Logarithm
echo log(100, 10); // 2 (log base 10)
echo log(M_E); // 1 (natural log)
echo log10(1000); // 3
echo log2(8); // 3

// exp() — e^x
echo exp(1); // 2.718... (e)
?>

4
Random Numbers — rand(), mt_rand(), random_int()
🎲
rand

Random Number Functions

rand() — Basic random। mt_rand() — Faster, better distribution। random_int() — Cryptographically secure (OTP, tokens के लिए)।

rand() — basic mt_rand() — faster random_int() — secure
RANDOM — EXAMPLES & USE CASES
<?php
// rand() — basic random
echo rand(); // 0 to RAND_MAX
echo rand(1, 100); // 1 to 100
echo rand(1, 6); // Dice roll 🎲

// mt_rand() — Mersenne Twister (4x faster)
echo mt_rand(1, 1000);

// random_int() — Cryptographically SECURE (PHP 7+)
echo random_int(100000, 999999); // 6-digit OTP

// OTP generate
function generateOTP(int $digits = 6): string {
  $min = (int) pow(10, $digits - 1);
  $max = (int) pow(10, $digits) - 1;
  return (string) random_int($min, $max);
}
echo generateOTP(); // e.g. 847293
echo generateOTP(4); // e.g. 5821

// Coupon code generate
function generateCoupon(int $length = 8): string {
  $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  $coupon = "";
  for ($i = 0; $i < $length; $i++) {
    $coupon .= $chars[random_int(0, strlen($chars) - 1)];
  }
  return $coupon;
}
echo generateCoupon(); // e.g. K8M2P5QR
?>
⚠️ Security: OTP, tokens, passwords के लिए हमेशा random_int() use करो — rand() या mt_rand() predictable हो सकते हैं।

5
Number Formatting — number_format(), sprintf()
💰
fmt

number_format()

Numbers को human-readable format में display करता है — decimal places, thousands separator। Price, statistics display के लिए ज़रूरी।

PHP 4+ Returns: string Display only
string number_format(
  float $num,
  int $decimals = 0,
  string $decimal_sep = ".",
  string $thousands_sep = ","
)
number_format() — EXAMPLES
<?php
// Basic
echo number_format(1234567.891); // 1,234,568
echo number_format(1234567.891, 2); // 1,234,567.89

// Indian format — lakh, crore
echo number_format(1234567.89, 2, ".", ","); // 1,234,567.89

// European format
echo number_format(1234567.89, 2, ",", "."); // 1.234.567,89

// Price display function
function formatPrice(float $amount, string $currency = "₹"): string {
  return $currency . number_format($amount, 2);
}
echo formatPrice(1299); // ₹1,299.00
echo formatPrice(99.5, "$"); // $99.50

// Percentage format
function formatPercent(float $val, int $decimals = 1): string {
  return number_format($val, $decimals) . "%";
}
echo formatPercent(12.345); // 12.3%

// Bytes to human readable
function formatBytes(int $bytes): string {
  return match(true) {
    $bytes >= pow(1024, 3) => round($bytes/pow(1024,3), 2) . " GB",
    $bytes >= pow(1024, 2) => round($bytes/pow(1024,2), 2) . " MB",
    $bytes >= 1024 => round($bytes/1024, 2) . " KB",
    default => $bytes . " B"
  };
}
echo formatBytes(1536000); // 1.46 MB
?>

6
Math Constants — M_PI, M_E, PHP_INT_MAX
MATH CONSTANTS — ALL IMPORTANT
<?php
// Mathematical constants
echo M_PI; // 3.1415926535898 (π)
echo M_E; // 2.718281828459 (e)
echo M_SQRT2; // 1.4142135623731 (√2)
echo M_LN2; // 0.69314718055995 (ln 2)
echo M_LOG2E; // log₂(e)

// PHP integer limits
echo PHP_INT_MAX; // 9223372036854775807 (64-bit)
echo PHP_INT_MIN; // -9223372036854775808
echo PHP_INT_SIZE; // 8 (bytes)
echo PHP_FLOAT_MAX; // 1.7976931348623E+308
echo PHP_FLOAT_EPSILON; // 2.2204460492503E-16

// Circle area और circumference
$radius = 7;
echo round(M_PI * $radius ** 2, 2); // 153.94 (area)
echo round(2 * M_PI * $radius, 2); // 43.98 (circumference)
?>

7
min(), max(), clamp — Range Functions
MIN, MAX, CLAMP — EXAMPLES
<?php
// min() — smallest value
echo min(5, 2, 8, 1); // 1
echo min([10, 20, 5, 30]); // 5
echo min("apple", "banana"); // apple (alphabetical)

// max() — largest value
echo max(5, 2, 8, 1); // 8
echo max([10, 20, 5, 30]); // 30

// Clamp — value को range में रखो
function clamp(float $val, float $min, float $max): float {
  return max($min, min($max, $val));
}
echo clamp(150, 0, 100); // 100
echo clamp(-5, 0, 100); // 0
echo clamp(50, 0, 100); // 50

// Real use — discount clamp
$discount = clamp(120, 0, 100); // Max 100% discount

// average
function average(array $nums): float {
  return count($nums) ? array_sum($nums) / count($nums) : 0;
}
echo round(average([85, 92, 78, 96]), 2); // 87.75
?>

8
Base Conversion — dec, hex, oct, bin
BASE CONVERSION — EXAMPLES
<?php
// Decimal → other bases
echo decbin(10); // 1010 (binary)
echo decoct(8); // 10 (octal)
echo dechex(255); // ff (hex)
echo dechex(16711680); // ff0000 (red color)

// Other bases → Decimal
echo bindec("1010"); // 10
echo octdec("17"); // 15
echo hexdec("ff"); // 255

// base_convert — any base to any
echo base_convert("ff", 16, 10); // 255 (hex→dec)
echo base_convert("255", 10, 16); // ff (dec→hex)

// CSS Color from RGB
function rgbToHex(int $r, int $g, int $b): string {
  return sprintf("#%02x%02x%02x", $r, $g, $b);
}
echo rgbToHex(79, 70, 229); // #4f46e5 (primary color!)
?>

9
Trigonometric Functions — sin, cos, tan
TRIGONOMETRY — deg2rad, sin, cos, tan
<?php
// PHP में angles radians में — deg2rad() convert करो
echo sin(deg2rad(90)); // 1
echo cos(deg2rad(0)); // 1
echo tan(deg2rad(45)); // 1 (approximately)

// rad2deg — radians to degrees
echo rad2deg(M_PI); // 180

// Haversine — Distance between two coordinates
function haversineDistance(float $lat1, float $lon1, float $lat2, float $lon2): float {
  $R = 6371; // Earth radius km
  $dLat = deg2rad($lat2 - $lat1);
  $dLon = deg2rad($lon2 - $lon1);
  $a = sin($dLat/2)**2 + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * sin($dLon/2)**2;
  return round($R * 2 * atan2(sqrt($a), sqrt(1-$a)), 2);
}
// Delhi to Mumbai distance
echo haversineDistance(28.6139, 77.2090, 19.0760, 72.8777) . " km";
// ~1147 km
?>

10
Real World — E-Commerce Calculations
COMBINED — Invoice & Statistics
<?php
// Invoice calculate करो
function calculateInvoice(array $items, float $gstRate = 18.0): array {
  $subtotal = array_sum(array_map(fn($i) => $i["price"] * $i["qty"], $items));
  $gstAmount = round($subtotal * $gstRate / 100, 2);
  $total = round($subtotal + $gstAmount, 2);
  $avgPrice = round($subtotal / count($items), 2);
  $maxPrice = max(array_column($items, "price"));
  $minPrice = min(array_column($items, "price"));
  return compact("subtotal", "gstAmount", "total", "avgPrice", "maxPrice", "minPrice");
}

$items = [
  ["name" => "PHP Book", "price" => 450, "qty" => 2],
  ["name" => "Laravel", "price" => 799, "qty" => 1],
  ["name" => "MySQL", "price" => 299, "qty" => 3],
];

$inv = calculateInvoice($items);
echo "Subtotal: ₹" . number_format($inv["subtotal"], 2); // ₹2,594.00
echo "GST 18%: ₹" . number_format($inv["gstAmount"], 2); // ₹466.92
echo "Total: ₹" . number_format($inv["total"], 2); // ₹3,060.92
echo "Avg: ₹" . number_format($inv["avgPrice"], 2); // ₹864.67
echo "Cheapest: ₹" . number_format($inv["minPrice"], 2); // ₹299.00
?>
Pattern: round() → financial। ceil() → pagination। floor() → age/floors। number_format() → display। random_int() → OTP/tokens।

Quick Reference — सभी Math Functions
FunctionकामExample → Output
abs()Absolute valueabs(-5) → 5
ceil()Round upceil(4.1) → 5
floor()Round downfloor(4.9) → 4
round()Nearest (decimal)round(3.14159, 2) → 3.14
pow()Power / **pow(2, 8) → 256
sqrt()Square rootsqrt(16) → 4
rand()Random intrand(1, 100) → 42
random_int()Secure randomrandom_int(100000, 999999)
number_format()Format for displaynumber_format(1234.5, 2) → 1,234.50
intdiv()Integer divisionintdiv(7, 2) → 3
fmod()Float remainderfmod(10.5, 3.2) → 0.9
min() / max()Smallest / Largestmin(3, 1, 4) → 1
log() / log10()Logarithmlog10(100) → 2
exp()e^xexp(1) → 2.718...
sin() cos() tan()Trigonometrysin(deg2rad(90)) → 1
dechex() hexdec()Base conversiondechex(255) → ff
is_numeric()Number checkis_numeric("42") → true

निष्कर्ष

PHP Math Functions रोज़ाना use होते हैं — invoices, statistics, pagination, OTPs। सही function सही जगह use करने से accurate results मिलते हैं।

round() — Financial calculations। 2 decimals हमेशा।

ceil() — Pagination, shipping slots। floor() — Age, categories।

random_int() — OTP, coupon codes। rand() नहीं — predictable है।

number_format() — Display के लिए। Calculation के लिए plain numbers use करो।

PHP_INT_MAX — Very large numbers के लिए bcmath extension use करो।

🚀 अगला Chapter: Chapter 21: PHP JSON & API — json_encode, json_decode, cURL, REST API बनाना और consume करना।