Advertisement

Google Ad Slot: content-top

PHP Math


There are various built-in functions available for performing mathematical operations. Here's an overview of some of the common PHP math functions:


Function

Description

Example

pi()

Returns the value of π (Pi), which is approximately 3.1415926535898

echo(pi())


Try it yourself

min() and max()

Returns the smallest or largest value in an array or a set of values

echo min(1, 2, 3, 4); // 1
echo max(1, 2, 3, 4); // 4


Try it yourself

abs()

Returns the absolute value of a number

echo abs(-10); // 10


Try it yourself

pow()

Returns the base raised to the power of the exponent

echo pow(2, 3); // 8


Try it yourself

sqrt()

Returns the square root of a number

echo sqrt(16); // 4


Try it yourself

round()

Rounds a floating-point number

echo round(3.1459, 2); // 3.15


Try it yourself

floor()

Rounds a number down to the nearest integer

echo floor(3.9); // 3


Try it yourself

ceil()

Rounds a number up to the nearest integer

echo ceil(3.1); // 4


Try it yourself

rand()

Function generates a random number

echo rand(); // Random number 


Try it yourself

rand() function with parameters:


However, you can also specify a range for the random number by passing two arguments: a minimum and maximum value.


Syntax


rand(int $min = 0, int $max = getrandmax())


  • $min: The minimum number in the range (inclusive). If not provided, it defaults to 0.
  • $max: The maximum number in the range (inclusive). If not provided, it defaults to getrandmax() (the largest possible random value).
Example
<!DOCTYPE html>
<html>
<body>
<?php
echo rand(1, 100); // Random number between 1 and 100
?>
</body>
</html>

Try it yourself