PHP provides built-in mathematical functions and constants for performing calculations, rounding numbers, working with trigonometric values, converting number bases, and generating random numbers.
- Arithmetic and Rounding: Calculate and round numbers using abs(), sqrt(), and round().
- Trigonometry and Conversion: Calculate trigonometric values and convert number bases.
- Random Numbers and Validation: Generate random numbers, use mathematical constants, and validate numeric values.
Perform Mathematical Operations Using PHP Functions
PHP provides built-in functions for common arithmetic operations and numerical calculations.
- abs() : Returns the absolute value of a number.
- ceil() : Rounds a number up to the nearest integer.
- floor() : Rounds a number down to the nearest integer.
- round() : Rounds a number to the nearest integer or specified decimal precision.
- min() : Returns the smallest value from the given values or an array.
- max() : Returns the largest value from the given values or an array.
- pow() : Raises a number to a specified power.
- sqrt() : Returns the square root of a number.
- intdiv() : Returns the integer quotient of a division.
- fmod() : Returns the floating-point remainder of a division.
- hypot() : Calculates the length of the hypotenuse using two or more dimensions.
<?php
echo abs(-15) . "\n";
echo ceil(4.2) . "\n";
echo floor(4.8) . "\n";
echo round(4.567, 2) . "\n";
echo sqrt(25) . "\n";
echo pow(2, 3) . "\n";
echo intdiv(10, 3) . "\n";
?>
Calculate Trigonometric and Logarithmic Values
PHP provides functions for trigonometric calculations, hyperbolic operations, and logarithmic computations.
- sin() : Returns the sine of an angle in radians.
- cos() : Returns the cosine of an angle in radians.
- tan() : Returns the tangent of an angle in radians.
- asin() : Returns the inverse sine of a value.
- acos() : Returns the inverse cosine of a value.
- atan() : Returns the inverse tangent of a value.
- atan2() : Calculates the angle from two coordinates.
- sinh() : Returns the hyperbolic sine of a value.
- cosh() : Returns the hyperbolic cosine of a value.
- tanh() : Returns the hyperbolic tangent of a value.
- asinh() : Returns the inverse hyperbolic sine.
- acosh() : Returns the inverse hyperbolic cosine.
- atanh() : Returns the inverse hyperbolic tangent.
- log() : Returns the natural logarithm or logarithm to a specified base.
- log10() : Returns the base-10 logarithm.
- log1p() : Calculates log(1 + x) with improved precision for small values.
- exp() : Returns Euler's number raised to a specified power.
- expm1() : Calculates exp(x) - 1 with improved precision for small values.
<?php
echo sin(deg2rad(30)) . "\n";
echo log10(100) . "\n";
echo exp(1) . "\n";
?>
Convert Numbers Between Different Bases
PHP provides functions to convert numbers between binary, decimal, octal, and hexadecimal representations.
- base_convert() : Converts a number from one base to another.
- bindec() : Converts a binary number to decimal.
- decbin() : Converts a decimal number to binary.
- decoct() : Converts a decimal number to octal.
- dechex() : Converts a decimal number to hexadecimal.
- hexdec() : Converts a hexadecimal number to decimal.
- octdec() : Converts an octal number to decimal.
<?php
echo decbin(10) . "\n";
echo bindec("1010") . "\n";
echo dechex(255) . "\n";
echo base_convert("1010", 2, 16) . "\n";
?>
Generate Random Numbers Using PHP
PHP provides functions for generating random numbers for simulations, testing, and other applications.
- rand() : Generates a pseudo-random integer within a specified range.
- mt_rand() : Generates a pseudo-random integer using the Mersenne Twister algorithm.
- random_int() : Generates a cryptographically secure random integer within a specified range.
- getrandmax() : Returns the maximum value returned by rand().
- mt_getrandmax() : Returns the maximum value returned by mt_rand().
- srand() : Seeds the random number generator used by rand().
- mt_srand() : Seeds the random number generator used by mt_rand().
- lcg_value() : Returns a pseudo-random floating-point number; this function is deprecated as of PHP 8.4.
<?php
echo rand(1, 100) . "\n";
echo mt_rand(1, 100) . "\n";
echo random_int(1, 100) . "\n";
?>
Use random_int() for security-sensitive operations, such as generating verification codes. For more advanced random number generation, PHP also provides the Random\Randomizer class.
Check Numeric Values Using PHP Functions
PHP provides functions and constants for identifying special floating-point values.
- is_finite() : Checks whether a value is finite.
- is_infinite() : Checks whether a value is positive or negative infinity.
- is_nan() : Checks whether a value is NAN (Not a Number).
- INF : Represents infinity.
- NAN : Represents a value that is not a number.
<?php
$value = sqrt(-1);
var_dump(is_nan($value)) . "\n";
var_dump(is_infinite(INF)) . "\n";
var_dump(is_finite(100.5)) . "\n";
?>
Use Predefined Mathematical Constants in PHP
PHP provides predefined mathematical constants for common calculations. Their availability can depend on the PHP build and platform.
- M_PI : Represents the mathematical constant pi.
- M_E : Represents Euler's number.
- M_EULER : Represents the Euler:Mascheroni constant.
- M_LNPI : Represents the natural logarithm of pi.
- M_LN2 : Represents the natural logarithm of 2.
- M_LN10 : Represents the natural logarithm of 10.
- M_LOG2E : Represents the base-2 logarithm of Euler's number.
- M_LOG10E : Represents the base-10 logarithm of Euler's number.
- M_PI_2 : Represents pi divided by 2.
- M_PI_4 : Represents pi divided by 4.
- M_1_PI : Represents the reciprocal of pi.
- M_2_PI : Represents 2 divided by pi.
- M_SQRTPI : Represents the square root of pi.
- M_2_SQRTPI : Represents 2 divided by the square root of pi.
- M_SQRT1_2 : Represents the square root of one-half.
- M_SQRT2 : Represents the square root of 2.
- M_SQRT3 : Represents the square root of 3.
<?php
echo M_PI . "\n";
echo M_E . "\n";
echo M_SQRT2 . "\n";
?>
Apply Best Practices When Using PHP Math Functions
- Validate Inputs: Check input types and ranges before performing calculations.
- Handle Floating-Point Precision: Avoid relying on exact equality comparisons for floating-point results.
- Use Secure Random Functions: Prefer random_int() over rand() or mt_rand() for security-sensitive values.
- Choose the Appropriate Rounding Mode: Use round() with the required precision and rounding behavior.
- Handle Invalid Results: Check for NAN, infinity, and invalid input values where necessary.
- Use Current APIs: Prefer supported alternatives when functions are deprecated, such as using Random\Randomizer instead of lcg_value() in PHP 8.4 and later.