pi()
Today, we will discuss the pi() function in PHP. This function is used to return the value of pi.
The pi() function returns the value of π (pi), the mathematical constant that describes the ratio of a circle's circumference to its diameter — approximately 3.1415926535898. This page covers its syntax, how it relates to the M_PI constant, and practical examples for circle and trigonometry math.
Syntax
pi(): floatThe function takes no arguments and returns a float. Because it never throws and never depends on input, you can call it anywhere you need the constant.
Basic Usage
PHP prints 3.1415926535898 by default. The stored value actually carries more precision than is shown — output is limited by the precision ini setting (14 significant digits by default).
pi() vs the M_PI Constant
PHP also exposes π as the predefined constant M_PI. The two are interchangeable — pi() simply returns M_PI:
<?php
var_dump(pi() === M_PI); // bool(true)
echo M_PI; // 3.1415926535898
?>Use whichever reads better in your code. M_PI is a constant lookup (marginally faster and conventional inside formulas), while pi() can be handy when you want a callable, for example passing it as a value.
Controlling Displayed Precision
The raw value has limited displayed digits, but you can format it as needed with round() or number_format():
<?php
echo round(pi(), 2); // 3.14
echo PHP_EOL;
echo number_format(pi(), 4); // 3.1416
?>Common Use Cases
pi() shines anywhere you do geometry or trigonometry.
Circumference and Area of a Circle
<?php
$radius = 5;
$circumference = 2 * pi() * $radius;
$area = pi() * $radius ** 2;
echo "Circumference: " . round($circumference, 4); // 31.4159
echo PHP_EOL;
echo "Area: " . round($area, 4); // 78.5398
?>Converting Degrees to Radians
PHP's trigonometric functions like sin() and cos() expect radians, not degrees. You can convert with π (or use the dedicated deg2rad() helper):
<?php
$degrees = 180;
$radians = $degrees * (pi() / 180);
echo $radians; // 3.1415926535898
echo PHP_EOL;
echo round(sin($radians), 4); // ~0 (sine of 180°)
?>Gotchas
- It takes no arguments.
pi(2)is not valid usage — the function ignores any input, so don't expect it to scale the value. - Floating-point limits apply. π is irrational; the returned
floatis an approximation. Avoid strict==comparisons with hand-typed decimals like3.14159— round both sides first. - Precision is a display setting, not the stored value. Changing the
precisionini directive changes how many digitsechoshows, not the accuracy of calculations.
Conclusion
pi() (and its equivalent M_PI constant) gives you a ready-to-use value of π for any geometry or trigonometry work in PHP. Pair it with round(), sqrt(), and pow() for cleaner math, and see the full PHP Math reference for related functions.