Find Percentage of a Number in PHP



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.

Example 1

The percentage of 300 with respect to 40% is calculated as (300 × 40) / 100 = 120.

Input
number=300;
percentage = 40;
Output
120

Example 2

The percentage of 300 with respect to 40% is calculated as (400 × 15) / 100 = 60.

Input
number=400;
percentage = 15;
Output
60

Below are different approaches for Finding the Percentage of a Number in PHP.

Direct Calculation Approach

This is the direct approach where we calculate the percentage of a number in PHP or any other programming language. In this approach, we directly multiply the given number by the percentage (we want to find) and divide the number by 100. This approach is simple and can be understood by beginners as it uses the multiplication (*) and division (\) operators to calculate the percentage.

Syntax

Following is the syntax for this approach ?

$result = ($number * $percentage) / 100;

Example

<?php
   $number = 500;
   $percentage = 10;
   $result = ($number * $percentage) / 100;
   echo "The percentage value is: " . $result;
?>

Output

The percentage value is: 50

Time Complexity : O(1)

Using Functions

In this approach, we use a function that takes a number and a percentage value as arguments and performs the calculation and returns the result. This approach is more organized and reusable. This function-based approach works best for larger programs.

Example

<?php
   function findPercentage($num, $percent) {
      return ($num * $percent) / 100;
   }
   $number = 600;
   $percentage = 25;
   $result = findPercentage($number, $percentage);
   echo "The percentage value is: " . $result;
?>

Output

The percentage value is: 150

Time Complexity : O(1)

Using a Class

Classes are a fundamental concept of object-oriented programming (OOP). We create a class that encapsulates the percentage calculation logic in its method. At last, we create an object to call the method and pass the number and percentage as arguments.

Example

<?php
   class PercentageCalculator {
      public function calculatePercentage($num, $percent) {
         return ($num * $percent) / 100;
      }
   }
   $obj = new PercentageCalculator();
   $number = 700;
   $percentage = 30;
   $result = $obj->calculatePercentage($number, $percentage);
   echo "The percentage value is: " . $result;
?>

Output

The percentage value is: 210

Time Complexity : O(1)

Updated on: 2025-03-24T14:12:01+05:30

621 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements