Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
PHP Program to Find the Percentage of a Number
In this problem, we are given a number and a percentage value, and we have to find the percentage of the given number. In this article, we are going to learn how we can calculate the percentage of a number in PHP using different approaches.
Understanding the Formula
To find the percentage of a number, we use the formula: (Number × Percentage) / 100
Example: The percentage of 300 with respect to 40% is calculated as (300 × 40) / 100 = 120.
Direct Calculation Approach
This is the direct approach where we calculate the percentage of a number using basic multiplication and division operators ?
Syntax
$result = ($number * $percentage) / 100;
Example
<?php $number = 500; $percentage = 10; $result = ($number * $percentage) / 100; echo "The percentage value is: " . $result; ?>
The percentage value is: 50
Using Functions
In this approach, we create a reusable function that takes a number and percentage as parameters and returns the calculated result ?
<?php
function findPercentage($num, $percent) {
return ($num * $percent) / 100;
}
$number = 600;
$percentage = 25;
$result = findPercentage($number, $percentage);
echo "The percentage value is: " . $result;
?>
The percentage value is: 150
Using Object-Oriented Approach
We can encapsulate the percentage calculation logic within a class for better organization and reusability ?
<?php
class PercentageCalculator {
public function calculatePercentage($num, $percent) {
return ($num * $percent) / 100;
}
}
$calculator = new PercentageCalculator();
$number = 700;
$percentage = 30;
$result = $calculator->calculatePercentage($number, $percentage);
echo "The percentage value is: " . $result;
?>
The percentage value is: 210
Comparison of Methods
| Method | Best Use Case | Time Complexity |
|---|---|---|
| Direct Calculation | Simple one-time calculations | O(1) |
| Function | Reusable calculations | O(1) |
| Class Method | Complex applications with OOP | O(1) |
Conclusion
All three approaches provide efficient ways to calculate percentages in PHP with O(1) time complexity. Choose the direct method for simple calculations, functions for reusability, and classes for object-oriented applications.
