Menu Close

Simple Arithmetic Operations using PHP

Here is the code for simple arithmetic operations using PHP like Addition, Subtraction, Multiplication and Division. These code samples are just for practice purpose, it may have issues or bugs.

<?php

function arithmetic_operations(int $op, float $x, float $y) : string {

 switch($op) {
 case 1 :
 /**
 * This is addition operation
 */
 $xy = $x + $y;
 echo "Addition of two numbers {$x} + {$y} = {$xy}" . PHP_EOL;
 break;

 case 2 :
 /**
 * This is subtraction operation
 */
 $xy = $x - $y;
 echo "Subtraction of two numbers {$x} - {$y} = {$xy}" . PHP_EOL ;
 break;

 case 3 :
 /**
 * This is multiplication operation
 */
 $xy = $x * $y;
 echo "Multiplication of two numbers {$x} * {$y} = {$xy}" . PHP_EOL;
 break;

 case 4 :
 /**
 * This is division operation
 */
 if ($y == 0) {
 echo "Divisor must not be zero, please re-run the process" . PHP_EOL;
 }
 else {
 $xy = $x / $y;
 echo "Division of two numbers {$x} / {$y} = {$xy}" . PHP_EOL;
 }
 break;

 default:
 echo "Something went wrong..." . PHP_EOL;

 }

 return "";
}

function select_opertion() {
 $op = (int) readline("Enter a number for the operation: ");

 if (!in_array($op, [1, 2, 3, 4])) {
 echo("Re-select a valid operation"). PHP_EOL;
 $op = select_opertion();
 }
 return $op;
}

$flow = true;

do {

 $x = (float) readline("Enter first number: ");
 $y = (float) readline("Enter second number: ");
 echo("1. Addition | 2. Subtraction | 3. Multiplication | 4. Division") . PHP_EOL;
 $op = select_opertion();
 print($op);

 arithmetic_operations($op, $x, $y);

 $con = readline("Do you want to continue: ");
 if ($con == "n") $flow = false;

} while ($flow);

Here we achieve these operations using switch case and functions in php. This code is expected to run on command line.

New methods in this article:

  1. readline – click on this and you will go to the documentation of this method.

Related Posts
Simple Arithmetic Operations using PHP
PHP cURL vs Guzzle: Which HTTP Client Should You Use?

Leave a Reply

Your email address will not be published. Required fields are marked *