PHP Maths
Sure! In PHP, you can perform mathematical operations using various built-in functions and operators. Here’s a rundown of some common math functions and operators in PHP, along with examples:
Basic Arithmetic Operators
-
Addition (+
)
$a = 5;
$b = 3;
$sum = $a + $b; // $sum is 8
echo $sum;
-
Subtraction (-
)
$a = 5;
$b = 3;
$difference = $a - $b; // $difference is 2
echo $difference;
-
Multiplication (*
)
$a = 5;
$b = 3;
$product = $a * $b; // $product is 15
echo $product;
-
Division (/
)
$a = 6;
$b = 3;
$quotient = $a / $b; // $quotient is 2
echo $quotient;
-
Modulus (%
)
$a = 7;
$b = 3;
$remainder = $a % $b; // $remainder is 1
echo $remainder;
Math Functions
-
abs()
- Absolute Value
$number = -5;
$absolute = abs($number); // $absolute is 5
echo $absolute;
-
ceil()
- Rounds a number up to the nearest integer
$number = 4.3;
$roundedUp = ceil($number); // $roundedUp is 5
echo $roundedUp;
-
floor()
- Rounds a number down to the nearest integer
$number = 4.7;
$roundedDown = floor($number); // $roundedDown is 4
echo $roundedDown;
-
round()
- Rounds a number to the nearest integer
$number = 4.5;
$rounded = round($number); // $rounded is 5
echo $rounded;
-
pow()
- Exponential (Power)
$base = 2;
$exponent = 3;
$result = pow($base, $exponent); // $result is 8
echo $result;
-
sqrt()
- Square Root
$number = 16;
$squareRoot = sqrt($number); // $squareRoot is 4
echo $squareRoot;
-
min()
and max()
- Minimum and Maximum of Values
$a = 5;
$b = 10;
$c = 3;
$minValue = min($a, $b, $c); // $minValue is 3
$maxValue = max($a, $b, $c); // $maxValue is 10
echo "Min: $minValue, Max: $maxValue";
-
rand()
- Generate a Random Integer
$randomNumber = rand(); // Generates a random number
echo $randomNumber;
Example: Calculating Area of a Circle
Here’s how you might use these functions to calculate the area of a circle with a given radius:
$radius = 7;
$area = pi() * pow($radius, 2); // Area = π * r^2
echo "The area of the circle is: " . $area;
In this example, pi()
returns the value of π, and pow()
is used to square the radius.
Feel free to ask if you need more detailed examples or explanations on any of these functions!