← Back to PHP Course | Chapter 14: Advanced PHP | Lesson 2 of 24

PHP Math Functions

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
<?php
echo round(4.5) . "\n";
echo ceil(4.1) . "\n";
echo floor(4.9);
?>

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
<?php
echo min(3, 1, 4) . "\n";
echo max([3, 1, 4]);
?>

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
<?php
echo rand(1, 10) . "\n";
echo random_int(1, 10);
?>

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
<?php
echo abs(-5) . "\n";
echo sqrt(16) . "\n";
echo pow(2, 3);
?>

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
<?php
echo base_convert("FF", 16, 2);
?>

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.