I've spent the last few evenings learning PHP, CSS and HTML through Codecademy and now on Team Treehouse. My goal is to progress with PHP over the next year or two and perhaps obtain Zend cert.
Anyway, I've worked on a simple calculator to test what I've learned. I'd like to see, (given the same 'functionality')what more experienced programmers would come up with. I think this would enhance my learning curve.
I've used a switch
statement, because I'm not sure if it's possible to do something like this:
Variable = Math Operator
Var1 = User Input
Var2 = User Input
Variable3 = Var1 Variable Var2
Example, if you entered *, 2, 2, Variable 3 would = 4.
I tried a few ways but could not make it work, so had to settle with a switch which seems cumbersome.
<?php
$input1 = $_GET["num1"];
$input2 = $_GET["num2"];
$input3 = $_GET["symbol"];
$mathinput = "Not Selected";
switch ($input3) {
case "*":
$input3 = "*";
$mathinput = "Multiplication";
$result = $input1 * $input2;
break;
case "/":
$input3 = "/";
$mathinput = "Division";
$result = $input1 / $input2;
break;
case "+":
$input3 = "+";
$mathinput = "Addition";
$result = $input1 + $input2;
break;
case "-":
$input3 = "-";
$mathinput = "Subtraction";
$result = $input1 - $input2;
break;
default:
$input3 = "0";
$mathinput = "Invalid Operator";
}
if ($input3=="0"){
echo '<div id="result"> <p>You have entered a bad operator</p> </div>' ;
}
else{
echo '<div id="result"> <p>Result: ' . $result . '</p> </div>';
}
?>