Home / Programs / Simple Calculator using PHP
🚀 Programming Example

Simple Calculator using PHP

👁 248 Views
💻 Practical Program
📘 Step Learning
Simple Calculator using PHP

💻 Program Code

<?PHP
class Calculator {
   
    public function add($number1, $number2){
       if(is_numeric($number1) && is_numeric($number2)){
           return $number1+$number2;
       }else{
           echo "values should be numeric.";
       }
    }
 
    public function subtract($number1, $number2){
        if(is_numeric($number1) && is_numeric($number2)){
             return $number1-$number2;
        }else{
              echo "values should be numeric.";
        }
    }
 
    public function multiply($number1, $number2){
        if(is_numeric($number1) && is_numeric($number2)){
              return $number1*$number2;
        }else{
             echo "values should be numeric.";
        }
    }
 
    public function divide($number1, $number2) {
          if(is_numeric($number1) && is_numeric($number2) && $number2 != 0){
            return $number1/$number2;
          }else{
             echo "Values should be numeric and divisor shouldn't be zero.";
          }
    }
}
 
$calc = new Calculator;
 
echo $calc->add(1,3);
echo "<br>";
echo $calc->subtract(4,3);
echo "<br>";
echo $calc->multiply(2,3);
echo "<br>";
echo $calc->divide(10,2);
 
?>
                        

🖥 Program Output

4
1
6
5
                            

📘 Explanation

📚 Learning Subject

Master Programming Through Practical Examples

Improve your coding logic, problem-solving skills and programming confidence by practicing real-world examples with explanations.

🎯 How to learn from this example

First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.

🔥 Practice suggestion

Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.