Home »
PHP
PHP Maths
By Shahnail Khan Last updated : December 5, 2023
In this tutorial, we will explore the fundamental aspects of PHP math. Understanding mathematical operations in PHP is important for performing calculations in your web applications. Let's explore various PHP math functions and learn how to execute arithmetic operations easily.
Basic Math in PHP
Before we dive into specific functions, let's cover the basics of PHP math. In PHP, you can perform common arithmetic operations like addition, subtraction, multiplication, and division using the standard operators: +, -, *, and /.
Example
This example demonstrates the mathematical operations in PHP.
<?php
$sum = 10 + 5; // Addition
$difference = 20 - 8; // Subtraction
$product = 6 * 4; // Multiplication
$quotient = 24 / 3; // Division
echo "Sum: $sum<br>"; // Print Sum
echo "Difference: $difference<br>"; // Print Difference
echo "Product: $product<br>"; // Print Product
echo "Quotient: $quotient<br>"; // Print Quotient
?>
The output of the above example is:
Sum: 15
Difference: 12
Product: 24
Quotient: 8
PHP Math Functions
Now, let's explore some PHP math functions that extend the capabilities of basic arithmetic. These functions make complex calculations easy and provide additional functionalities.
This figure displays the basic PHP Math functions widely used in PHP scripts.
Each math function performs different operations.
- 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.
- sqrt(): Calculates the square root of a number.
- decbin(): Converts a decimal number to binary.
- dechex(): Converts a decimal number to hexadecimal.
- decoct(): Converts a decimal number to octal.
- base_convert(): Converts a number from one base to another.
- bindec(): Converts a binary number to decimal.
There are many functions available. Click here to know more.
PHP Maths: More Examples
Now, let's take some examples to know how to use these math functions in PHP.
Example 1
<?php
// abs() - Absolute Value
$number = -208;
$absoluteValue = abs($number);
echo "abs(-208) = $absoluteValue<br>";
// ceil() and floor() - Rounding
$decimalNumber = 7.3;
$roundedUp = ceil($decimalNumber);
$roundedDown = floor($decimalNumber);
echo "ceil(7.3) = $roundedUp<br>";
echo "floor(7.3) = $roundedDown<br>";
// sqrt() - Square Root
$originalNumber = 25;
$squareRoot = sqrt($originalNumber);
echo "sqrt(25) = $squareRoot<br>";
// decbin(), dechex(), decoct() - Number Conversions
$decimalNumber = 150;
$binaryRepresentation = decbin($decimalNumber);
$hexadecimalRepresentation = dechex($decimalNumber);
$octalRepresentation = decoct($decimalNumber);
echo "decbin(150) = $binaryRepresentation<br>";
echo "dechex(150) = $hexadecimalRepresentation<br>";
echo "decoct(150) = $octalRepresentation<br>";
// base_convert() - Base Conversion
$numberToConvert = "2a"; // Hexadecimal representation
$decimalConverted = base_convert($numberToConvert, 16, 10);
echo "base_convert('2a', 16, 10) = $decimalConverted<br>";
// bindec() - Binary to Decimal
$binaryNumber = "1101";
$decimalFromBinary = bindec($binaryNumber);
echo "bindec('1101') = $decimalFromBinary<br>";
?>
The output of the above example is:
abs(-208) = 208
ceil(7.3) = 8
floor(7.3) = 7
sqrt(25) = 5
decbin(150) = 10010110
dechex(150) = 96
decoct(150) = 226
base_convert('2a', 16, 10) = 42
bindec('1101') = 13
This example demonstrates some PHP Math Functions, where each function serves specific purpose.
- abs() - Absolute Value: Calculates the absolute value of -208, which is 208.
- ceil() and floor() - Rounding: Rounds the decimal number 7.3 up (ceil) to 8 and down (floor) to 7.
- sqrt() - Square Root: Computes the square root of 25, which is 5.
- decbin(), dechex(), decoct() - Number Conversions: Converts the decimal number 15 to its binary, hexadecimal, and octal representations.
- base_convert() - Base Conversion: Converts the hexadecimal number '2a' to its decimal equivalent (42).
- bindec() - Binary to Decimal: Converts the binary number '1101' to its decimal equivalent (13).
Each echo statement displays the result of the corresponding operation. You can run this code to see the output for each math function.
Example 2
Question: You are developing a basic PHP program to handle numeric data for a small business. The application needs to perform various mathematical operations and conversions based on user inputs. Your task is to create a simple numeric utility with the following functionalities:
- Calculate Total Cost: Allow users to input the quantity and unit price of an item. The application should calculate and display the total cost using the formula: total cost = quantity * unit price.
- Round and Display Discount: Users should be able to input a decimal discount rate (e.g., 0.15 for 15%). The application should round the discount to the nearest integer using the round() function and display the result.
- Calculate Compound Interest: Allow users to input the principal amount, interest rate, and the number of years. The application should calculate and display the compound interest using the formula: compound interest = principal * (1 + rate/n)^(nt) - principal, where n is the number of times interest is compounded per year, and t is the number of years.
Solution:
Read the question carefully. Once you read, think of the easiest approach to solve the problem.
For this question, we can use basic PHP Math functions namely, round() and pow().
<?php
// Calculate Total Cost
$quantity = 10;
$unitPrice = 25.5;
$totalCost = $quantity * $unitPrice;
echo "Total Cost: $totalCost <br>";
// Round and Display Discount
$discountRate = 0.15;
$roundedDiscount = round($discountRate * 100); // Convert to percentage and round
echo "Rounded Discount: $roundedDiscount% <br>";
// Calculate Compound Interest
$principal = 1000;
$interestRate = 0.06;
$years = 3;
$compoundedPerYear = 4; // Quarterly compounding
$compoundInterest =
$principal *
pow(
1 + $interestRate / $compoundedPerYear,
$compoundedPerYear * $years
) -
$principal;
echo "Compound Interest: $compoundInterest <br>";
?>
The output of the above example is:
Total Cost: 255
Rounded Discount: 15%
Compound Interest: 195.61817146153
This solution demonstrates how to perform various calculations and operations based on the problem statement. Each operation is carried out in line without using separate function statements.