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
How to Add Two Numbers in PHP Program?
In PHP, adding two numbers is a fundamental arithmetic operation that can be performed using various approaches. This article demonstrates different methods to add two numbers in PHP programming.
Basic Addition Example
Before exploring different approaches, let's look at a simple example
<?php
$number1 = 8;
$number2 = 12;
$result = $number1 + $number2;
echo "Result: " . $result;
?>
Result: 20
The addition of 8 + 12 gives 20 as the result. Now let's explore different approaches to implement this operation.
Method 1: Direct Addition
This is the simplest approach using the plus (+) operator directly between two variables ?
Syntax
$result = $number1 + $number2;
Example
<?php
// Define two numbers
$number1 = 10;
$number2 = 4;
// Perform addition
$result = $number1 + $number2;
// Display the result
echo "The result of addition is: " . $result;
?>
The result of addition is: 14
Time Complexity: O(1)
Space Complexity: O(1)
Method 2: Using Functions
This approach uses a function to encapsulate the addition logic, making code more organized and reusable ?
<?php
// Function to add two numbers
function addTwoNumbers($a, $b) {
return $a + $b;
}
// Define numbers
$number1 = 15;
$number2 = 9;
// Call function and store result
$result = addTwoNumbers($number1, $number2);
// Display the result
echo "The result of addition is: " . $result;
?>
The result of addition is: 24
Time Complexity: O(1)
Space Complexity: O(1)
Method 3: Using Object-Oriented Approach
This method uses object-oriented programming concepts, creating a class with a method to perform addition ?
<?php
// Define the Addition class
class Addition {
// Method to perform addition
public function addTwoNumbers($a, $b) {
return $a + $b;
}
}
// Create an object of the Addition class
$obj = new Addition();
// Input numbers
$number1 = 20;
$number2 = 8;
// Call the add method using the object
$result = $obj->addTwoNumbers($number1, $number2);
// Display the result
echo "The result of addition is: " . $result;
?>
The result of addition is: 28
Time Complexity: O(1)
Space Complexity: O(1)
Comparison
| Method | Best For | Reusability | Complexity |
|---|---|---|---|
| Direct Addition | Simple calculations | Low | Very Simple |
| Function | Reusable code blocks | High | Simple |
| Class Method | OOP applications | Very High | Moderate |
Conclusion
All three methods achieve the same result with O(1) complexity. Choose direct addition for simple scripts, functions for reusable code, and classes for object-oriented applications. The plus operator (+) remains the core mechanism in all approaches.
