PHP ยท Chapter 10 of 44

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.

Syntax
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.

Example 1 (php)
<?php
  echo max(5, 10, 2);
?>
Output
10

max() returns the largest of the given numbers.

Example 2 (php)
<?php
  echo round(3.14159, 2);
?>
Output
3.14

round() 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.
๐Ÿ’ก Note: Use random_int() instead of rand() when randomness needs to be cryptographically secure, such as for tokens.

๐Ÿ“ Quick Quiz

1. Which function rounds a number to a set number of decimals?

2. Which function returns the largest of several values?

3. Which function generates a cryptographically secure random integer?