Open In App

PHP Program to Add Two Numbers

Given two numbers, the task is to add two numbers in PHP. It is one of the most basic arithmetic operations and a fundamental concept in programming.

Examples:

Input: num1 = 10, num2 = 20
Output: sum = 30

Input: num1 = 70, num2 = 120
Output: sum = 190

Using + operator

The simplest way to add two numbers in PHP is by using variables to store the numbers and then adding them using the "+" operator.

Example: This function illustrates the above mentioned approach to Add two numbers.

<?php

// Define two numbers
$num1 = 10;
$num2 = 20;

// Add the numbers
$sum = $num1 + $num2;

// Display the result
echo "The sum of $num1 and $num2 is: $sum";

?>

Output
The sum of 10 and 20 is: 30

Using Arrays and Array Functions

Another approach to add two numbers in PHP is by using arrays and array functions. This method is particularly useful when you want to add more than two numbers or when the numbers are already stored in an array.

Example: This function illustrates the above mentioned approach to Add two numbers.

<?php

// Define an array containing 
// the numbers to be added
$nums = [10, 20];

// Use array_sum() to add the numbers
$sum = array_sum($nums);

// Display the result
echo "The sum of " . implode(" and ", $nums) . " is: $sum";

?>

Output
The sum of 10 and 20 is: 30

Using Bitwise Operator

We will use Bitwise Operator to add two numbers. First, we check num2 is not equal to zero, then Calculate the carry using & operator, and then use XOR operator to get sum of numbers. At last, shift the carry to 1 left.

Example: This function illustrates the above mentioned approach to Add two numbers.

<?php

function add($num1, $num2) {
    while ($num2 != 0) {
        $carry = $num1 & $num2;
        $num1 = $num1 ^ $num2;
        $num2 = $carry << 1;
    }
    
    return $num1;
}

// Given data
$num1 = 15;
$num2 = 32;

$sum = add($num1, $num2);
// Displaying the result
echo "Sum of $num1 and $num2: $sum";

?>

Output
Sum of 15 and 32: 47
Article Tags :