HOME HTML EDITOR C JAVA PHP

PHP Math Functions

PHP has a set of built-in math functions that allow you to perform mathematical tasks on numbers. These functions make it easy to handle complex calculations without writing long code.

1. The pi() Function

The pi() function returns the value of PI (approximately 3.14159...).

<?php
  echo pi(); // Outputs: 3.1415926535898
?>

2. min() and max() Functions

The min() and max() functions can be used to find the lowest or highest value in a list of arguments.

<?php
  echo min(0, 150, 30, 20, -8, -200); // Outputs: -200
  echo max(0, 150, 30, 20, -8, -200); // Outputs: 150
?>

3. The abs() Function

The abs() function returns the absolute (positive) value of a number.

<?php
  echo abs(-6.7); // Outputs: 6.7
?>

4. The sqrt() Function

The sqrt() function returns the square root of a number.

<?php
  echo sqrt(64); // Outputs: 8
?>

5. The round() Function

The round() function rounds a floating-point number to its nearest integer.

<?php
  echo round(0.60); // Outputs: 1
  echo round(0.49); // Outputs: 0
?>

6. Random Numbers - rand()

The rand() function generates a random number. If you want a random number between 10 and 100, use rand(10, 100).

<?php
  echo rand();
  echo rand(10, 100);
?>
Note: Mathematical functions are very useful when creating dynamic applications like shopping carts (for tax/discount calculations) or games (for random scores).