Open In App

PHP Program to Perform Arithmetic Operations

Last Updated : 20 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

This article will show you how to perform arithmetic operations in PHP. The arithmetic operators are used to perform simple mathematical operations like addition, subtraction, multiplication, etc.

Arithmetic Operators

Operator Name

Syntax

Description

Addition

$x + $y

The addition operator is used to add both operands.

Subtraction

$x – $y

The subtraction operator is used to subtract the second operand from the first operand.

Multiplication

$x * $y

The multiplication operator is used to multiply both operands.

Division

$x / $y

The division operator is used to divide the first operand by second operand.

Exponentiation

$x ** $y

The exponentiation operator is used to calculate exponent of first operands to the power second operand.

Modulus

$x % $y

The modulus operator is used to calculate the remainder of the operand.

Example 1: This example will show the implementation of arithmetic operator.

PHP




<?php
  
$x = 10;
$y = 4;
  
// Performs Arithmetic operations
// and display the result
echo($x + $y) . "\n";
echo($x - $y) . "\n";
echo($x * $y) . "\n";
echo($x / $y) . "\n";
echo($x ** $y) . "\n";
echo($x % $y);
  
?>


Output

14
6
40
2.5
10000
2

Example 2: This example will show the implementation of arithmetic operators using switch case.

PHP




<?php
  
$x = 10;
$y = 4;
  
$operator = "*";
  
switch ($operator) {
    case "+":
        echo $x + $y;
        break;
    case "-":
        echo $x - $y;
        break;
    case "*":
        echo $x * $y;
        break;
    case "/":
        echo $x / $y;
        break;
    case "**":
        echo $x ** $y;
        break;
    case "%":
        echo $x % $y;
        break;
    default:
        echo "Incorrect Operator";
        break;
}
  
?>


Output

40



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads