PHP Math Functions
PHP includes many built-in math functions for common operations, such as finding the largest or smallest of several values, rounding numbers, and generating random numbers.
These functions save you from writing your own logic for common tasks and are optimized for performance, making them the preferred way to handle numeric operations in PHP.
round($num, $precision);
rand($min, $max);Common math functions
max() and min() find the largest and smallest values, round() rounds a float to a given precision, and sqrt() calculates a square root.
Random numbers
rand() or the more secure random_int() generate random integers, which are useful for things like generating random tokens or shuffling data.
<?php
echo max(5, 10, 2);
?>10max() returns the largest of the given numbers.
<?php
echo round(3.14159, 2);
?>3.14round() rounds the number to 2 decimal places.
Key points
- max() and min() return the largest and smallest values.
- round() rounds a float to a chosen number of decimal places.
- rand() and random_int() generate random integers.
- PHP's math functions are optimized and preferred over manual calculations.
