PHP log() function


The log() function in PHP is used to calculate the logarithm of a number. By default, it computes the natural logarithm (base e), but it can also calculate logarithms in other bases if specified.

Syntax:

log(float $number, float|null $base = null): float
  • $number: The number for which you want to compute the logarithm. This must be greater than zero.
  • $base: (optional) The base of the logarithm. If not provided, the function computes the natural logarithm (base e). If specified, it calculates the logarithm of $number with respect to the given base.
  • Return Value: Returns the logarithm of the number as a float.

Example 1: Natural Logarithm

<?php echo log(10); ?>

Output:

2.302585092994046

Explanation: This calculates the natural logarithm of 10, which is approximately 2.3026.

Example 2: Logarithm with a Specified Base

<?php echo log(100, 10); ?>

Output:

2

Explanation: This calculates the logarithm of 100 to the base 10, which is 2, because 102=10010^2 = 100.

Example 3: Logarithm of a Fraction

<?php echo log(0.1, 10); ?>

Output:

-1

Explanation: The logarithm of 0.1 to the base 10 is -1, because 101=0.110^{-1} = 0.1.

Example 4: Using Different Bases

<?php echo log(64, 2); ?>

Output:

6

Explanation: This calculates the logarithm of 64 to the base 2, which is 6, because 26=642^6 = 64.

Example 5: Logarithm of a Negative Number

<?php echo log(-10); ?>

Output:

Warning: log(): Argument 1 should be greater than 0

Explanation: The logarithm of a negative number is undefined in real numbers, resulting in a warning.

Key Points:

  • Domain: The input number must be greater than 0; otherwise, a warning is issued.
  • Base: If the base is not specified, the default is the natural logarithm (base e). You can specify any positive number as the base.
  • Usage: Logarithms are widely used in mathematics, particularly in calculations involving exponential growth, decay processes, and in algorithms (like those used in computer science).

Example of Practical Use:

<?php $population = 100000; $growthRate = 1.05; // 5% growth rate $years = 10; // Calculate the expected population after 10 years $expectedPopulation = $population * pow($growthRate, $years); echo "Expected Population: " . $expectedPopulation . "\n"; // Use logarithm to find how many years it will take to double the population $doublePopulation = $population * 2; $yearsToDouble = log($doublePopulation / $population) / log($growthRate); echo "Years to double the population: " . $yearsToDouble; ?>

Output:

Expected Population: 162889.462679 Years to double the population: 14.206699292272

Explanation: This example shows how to use the log() function to calculate the number of years it will take to double a population based on a specified growth rate.

In summary, log() is a powerful function in PHP for computing logarithms, useful in various mathematical and real-world applications where exponential relationships are involved.