PHP Math Functions
In this page:
Basic Rounding Functions
round(), ceil(), and floor() all turn a float into a whole number but disagree on direction: round() picks the nearest integer, ceil() always rounds up, and floor() always rounds down, which matters for things like billing calculations.
Example: Basic Rounding Functions
<?php
echo round(4.5) . "\n";
echo ceil(4.1) . "\n";
echo floor(4.9);
?>
Login to try C/C++/Java/PHP code in the editor
Minimum and Maximum Values
min() and max() accept either a list of separate arguments or a single array, returning the smallest or largest value found -- handy for clamping a value into an allowed range.
Example: Minimum and Maximum Values
<?php
echo min(3, 1, 4) . "\n";
echo max([3, 1, 4]);
?>
Login to try C/C++/Java/PHP code in the editor
Random Number Generation
rand() is fine for non-critical randomness like shuffling a quiz, but random_int() uses a cryptographically secure source and should be preferred anywhere randomness affects security, like generating a token.
Example: Random Number Generation
<?php
echo rand(1, 10) . "\n";
echo random_int(1, 10);
?>
Login to try C/C++/Java/PHP code in the editor
Absolute and Power Calculations
abs() strips a number's sign, sqrt() computes a square root, and pow() raises a base to a given exponent -- together covering the calculations that show up constantly in geometry and finance code.
Example: Absolute and Power Calculations
<?php
echo abs(-5) . "\n";
echo sqrt(16) . "\n";
echo pow(2, 3);
?>
Login to try C/C++/Java/PHP code in the editor
Mathematical Conversions
base_convert() converts a number between arbitrary numeric bases (like hex to binary), which is useful when working with color codes, bitmasks, or other data that's naturally expressed in a non-decimal base.
Example: Mathematical Conversions
<?php
echo base_convert("FF", 16, 2);
?>
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 24 topics to unlock
0/24 topics done
Complete these topics first:
- PHP Date & Time
- PHP Math Functions
- PHP JSON Handling
- PHP XML Handling
- PHP cURL Introduction
- PHP REST API Basics
- PHP Composer & Packages
- PHP Autoloading
- PHP Design Patterns
- PHP MVC Architecture
- PHP Security Best Practices
- PHP Performance Optimization
- PHP 8 New Features
- PHP Type Declarations
- PHP Match Expression Advanced
- PHP Fibers
- PHP Attributes
- PHP Magic Constants
- PHP Include & Require
- PHP Iterables
- PHP SimpleXML Parser
- PHP SimpleXML Get
- PHP XML Expat Parser
- PHP DOM Parser