In PHP, log() returns the logarithm of a number. By default it gives the natural logarithm, which uses the base e.
A logarithm answers the question: "What power do I raise the base to, to get this number?" Pass a second argument if you want a different base, such as 2 or 10.
Syntax
Call log() with the values you need. Start with this line.
PHP
$result = log(100, 10);
Call
What it does
log(M_E)
Returns 1, because e raised to the power 1 is e.
log(100, 10)
Returns 2, because 10 raised to the power 2 is 100.
log(8, 2)
Returns 3, because 2 raised to the power 3 is 8.
log($x) with no base is the natural logarithm. If you only need base 10 or base 2, log10() and log2-style calls like log($x, 2) are easy to read. A base of 0 or less throws a ValueError in PHP 8.
Library declarations
PHP
log(float $num, float $base = M_E): float
Parameters
Parameter
Description
num
Required. The number to take the logarithm of. It should be greater than 0.
base
Optional. The base of the logarithm. The default is M_E (about 2.71828), which gives the natural logarithm.
Return Value
Return Value
Description
float
The logarithm of num. Returns -INF for 0 and NAN for negative numbers.
PHP Examples
Example 1 — Natural Log and Custom Bases
Call log() with one argument for the natural logarithm, or add a base as the second argument.
Doubling means growing by a factor of 2, so we use log(2).
Divide by log(1 + $rate) to get the number of years.
Round to two decimals and print the result.
Frequently Asked Questions
log() returns the logarithm of a number. With one argument it returns the natural logarithm (base e). With a second argument it uses that base instead.
Pass 2 as the second argument, for example log(8, 2), which returns 3. This works for any base greater than 0 except 1.
log() uses base e by default, while log10() always uses base 10. log($x, 10) gives the same result as log10($x), but log10() is shorter and clearer.
Logarithms are not defined for negative numbers, so PHP returns NAN. For 0 the result goes toward negative infinity, so PHP returns -INF.
Yes. PHP does not have a function called ln(). The one-argument form of log() is the natural logarithm, which mathematicians write as ln.