Welcome to our comprehensive guide on PHP Math Functions! In this lesson, we'll dive into the world of mathematical operations and functions in PHP. By the end of this tutorial, you'll be able to perform various calculations, manipulate numbers, and understand the importance of these functions in real-world programming.
Let's get started!
PHP provides a rich set of built-in math functions to perform various mathematical operations. These functions are part of the math extension and are prefixed with math_. However, for ease of use and better readability, we'll use the shorthand versions, which are not prefix-free but easier to remember and more commonly used.
Before we dive into the functions, let's quickly review basic arithmetic operations in PHP.
$a + $b$a - $b$a * $b$a / $b$a % $b$a ** $bNow, let's explore some of the most useful math functions in PHP.
abs(): Absolute ValueThe abs() function returns the absolute value of a number. In other words, it returns the value without regard to its sign.
<?php
$num1 = -10;
$num2 = 3.5;
echo "Absolute value of -10: ", abs($num1), "\n";
echo "Absolute value of 3.5: ", abs($num2), "\n";
?>Output:
Absolute value of -10: 10
Absolute value of 3.5: 3.5
round(): Rounding NumbersThe round() function rounds a number to the nearest integer. You can also specify the number of decimal places to round to.
<?php
$num1 = 7.3;
$num2 = 3.8;
echo "Rounding 7.3: ", round($num1), "\n";
echo "Rounding 3.8: ", round($num2), "\n";
echo "Rounding 7.3 to 2 decimal places: ", round($num1, 2), "\n";
echo "Rounding 3.8 to 1 decimal place: ", round($num2, 1), "\n";
?>Output:
Rounding 7.3: 7
Rounding 3.8: 4
Rounding 7.3 to 2 decimal places: 7.3
Rounding 3.8 to 1 decimal place: 3.8
sqrt(): Square RootThe sqrt() function calculates the square root of a number.
<?php
$num = 16;
echo "Square root of 16: ", sqrt($num), "\n";
?>Output:
Square root of 16: 4
ceil() and floor(): Rounding Up and DownThe ceil() function rounds a number up to the nearest integer, while floor() rounds a number down to the nearest integer.
<?php
$num1 = 9.2;
$num2 = -9.2;
echo "Ceiling of 9.2: ", ceil($num1), "\n";
echo "Floor of 9.2: ", floor($num1), "\n";
echo "Ceiling of -9.2: ", ceil($num2), "\n";
echo "Floor of -9.2: ", floor($num2), "\n";
?>Output:
Ceiling of 9.2: 10
Floor of 9.2: 9
Ceiling of -9.2: -9
Floor of -9.2: -10
What will be the output of `round(3.5, 1)`?
Write a PHP script that calculates the area of a circle given the radius. Use the pi() function, pow() function for exponentiation, and round() function to round the area to two decimal places.
<?php
// Practice Exercise
function circleArea($radius) {
$area = pi() * pow($radius, 2);
return round($area, 2);
}
$radius = 5;
echo "Area of circle with radius 5: ", circleArea($radius), "\n";
?>Output:
Area of circle with radius 5: 78.54
Remember, practice makes perfect! Keep exploring, and happy coding! π―ππ