Chapter 27. Performing Math with PHP
In Chapter 9, we covered the most basic aspects of mathematics in PHP: the numerical types, the basic arithmetic operators, a small set of arithmetic functions, and (because it is so widely used in web scripting) pseudo-random number generation. In this chapter, we round out this coverage by enumerating the built-in mathematical constants; exploring trigonometric, logarithmic, and base conversion functions, and explaining PHP's bc module for arbitrary-precision arithmetic.
Mathematical Constants
When we wrote the first edition of this book (around the release of PHP version 4.0), there was only one documented math constant: M_PI
(the value of pi as a double). However, many new constants were introduced with PHP v4.0.2. Most of these new constants had to do with pi (or multiples thereof), e
(or multiples thereof), or square roots, with a few oddballs thrown in. The list has since shrunk back down to a slightly smaller number of predefined mathematical constants, for a variety of reasons. Those that remain are listed in Table 27-1. The general naming scheme is M_<constant-name>
. In cases where the constant is a ratio (x/y), the name is M_X_Y
, and in cases where there is an operation on a number, the name is M_OPERNUM
(for example, M_SQRT2
).
Table 27-1. Mathematical Constants
Constant | Description |
| Pi |
| pi/2 |
|
Get PHP6 and MySQL® 6 Bible now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.