php basic calculator with function and switch but result is - php

i am currently doing some simple calculator for a practice but it the output or result is not showing here is my code guys hope you can help me :/
<input type="radio" value= "Addition" name="calcu"> Addition .<br />
<input type="radio" value= "Subtraction" name="calcu"> Subtraction .<br />
<input type="radio" value= "Multiplication" name="calcu"> Multiplication .<br />
<input type="radio" value= "Division" name="calcu"> Division .<br />
<?php
$num1 = $_POST['num1'];
$num2 = $_POST['num2'];
$calcu = $_POST['calcu'];
function calculate($n1,$n2)
{
switch('$calcu')
{
case "Addition";
$compute = $n1 + $n2;
break;
case "Subtraction";
$compute = $n1 - $n2;
break;
case "Multiplication";
$compute = $n1 * $n2;
break;
case "Division";
$compute = $n1 / $n2;
break;
}
}
echo "$calcu <br /> <br /> 1st Number: $num1 <br /> 2nd Number: $num2 <br /><br />";
echo "Answer is:" .calculate($num1,$num2);
?>

Here is complete code:
<?php
$num1 = $_POST['num1'];
$num2 = $_POST['num2'];
$calcu = $_POST['calcu'];
function calculate($n1,$n2, $calcu) // set $calcu as parameter
{
switch($calcu)
{
case "Addition": // here you have to use colons not semi-colons
$compute = $n1 + $n2;
break;
case "Subtraction":
$compute = $n1 - $n2;
break;
case "Multiplication":
$compute = $n1 * $n2;
break;
case "Division":
$compute = $n1 / $n2;
break;
}
return $compute; // returning variable
}
echo "$calcu <br /> <br /> 1st Number: $num1 <br /> 2nd Number: $num2 <br /><br />";
echo "Answer is:" .calculate($num1,$num2, $calcu); // you need to pass $calcu as argument of that function
?>

Change switch('$calcu') to switch($calcu). It should be this way.
But not only that. Your variables are undefined because you are trying to address them before form is submited, i.e they don't exist yet.
$num1 = $_POST['num1'];
$num2 = $_POST['num2'];
$calcu = $_POST['calcu'];
And there you address them
echo "$calcu <br /> <br /> 1st Number: $num1 <br /> 2nd Number: $num2 <br /><br />";
echo "Answer is:" .calculate($num1,$num2);
The right way to implement this is to check if form was submitted:
<input type="radio" value= "Addition" name="calcu"> Addition .<br />
<input type="radio" value= "Subtraction" name="calcu"> Subtraction .<br />
<input type="radio" value= "Multiplication" name="calcu"> Multiplication .<br />
<input type="radio" value= "Division" name="calcu"> Division .<br />
<?php
if (isset($_POST)){
$num1 = $_POST['num1'];
$num2 = $_POST['num2'];
$calcu = $_POST['calcu'];
function calculate($n1,$n2)
{
switch('$calcu')
{
case "Addition";
$compute = $n1 + $n2;
break;
case "Subtraction";
$compute = $n1 - $n2;
break;
case "Multiplication";
$compute = $n1 * $n2;
break;
case "Division";
$compute = $n1 / $n2;
break;
}
}
echo "$calcu <br /> <br /> 1st Number: $num1 <br /> 2nd Number: $num2 <br /><br />";
echo "Answer is:" .calculate($num1,$num2);
unset($_POST);
}
?>

Change switch('$calcu') to switch($calcu).
As #PeterM mentioned, you are accessing variable $calcu out of scope. Either you pass the $calcu variable to fun calculate or access directly by $_POST array.
use switch($_POST['calcu']).
OR
function calculate($n1,$n2, $calcu) {
...
}
Call the fun by calculate($n1,$n2, $calcu).

Related

Can we use Arithmetic Operators ( + - * / ) in Switch Statement in PHP?

I was trying to make a calculator and wanted to use Arithmetic Operators in the switch Statement but i am not able to.
Can someone help me out.
Error:
Warning: Undefined array key "num2" in on line 16
220
Fatal error: Uncaught DivisionByZeroError: Division by zero in 27 Stack trace: #0 {main} thrown on line 27
<!DOCTYPE html>
<html>
<body>
<form action="php.php" method="post">
Number 1: <input type="number" name="num1"><br>
Operator: <input type="text" name="op"><br>
Number 3: <input type="number" name="num1"><br><br>
<input type="submit">
</form>
<?php
$num1 = $_POST["num1"];
$op = $_POST["op"];
$num2 = $_POST["num2"];
switch($op)
{
case "+":
echo $num1 + $num2;
case "-":
echo $num1 - $num2;
case "*":
echo $num1 * $num2;
case "/":
echo $num1 / $num2;
}
?>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<form action="php.php" method="GET">
Number 1: <input type="number" name="num1"><br>
Operator: <input type="text" name="op"><br>
Number 3: <input type="number" name="num2"><br><br>
<input type="submit">
</form>
<?php
$num1 = $_GET['num1'];
$op = $_GET['op'];
$num2 = $_GET['num2'];
switch($op)
{
case '+':
echo $num1 + $num2;
break;
case '-':
echo $num1 - $num2;
break;
case '*':
echo $num1 * $num2;
break;
case '/':
echo $num1 / $num2;
break;
}
?>
</body>
</html>
Put break after every case
These was a naming error in the code with the names of the variables. eg num1 and num2. Name them correctly

A non numeric value encountered in ..... on line 35

This is the code that I'm using. All the arithemetic operations are done successfully except subtraction. When Subtraction is selected, it gives the error. If I use two different echo statements, one for "The answer is: " and the other echo statement for the subtraction between two variables, it gives no error. What is the reason behind the generation of this error when both the variables string are printed using one echo statement??
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Calculator</title>
</head>
<body>
<form>
<input type="text" name="num1" placeholder="First Number">
<input type="text" name="num2" placeholder="Second Number">
<select name="operator">
<option>None</option>
<option>Add</option>
<option>Subtract</option>
<option>Multiply</option>
<option>Divide</option>
</select>
<br>
<button name="submit" value="submit">Calculate</button>
</form>
<?php
if (isset($_GET['submit'])) {
$num1 = $_GET['num1'];
$num2 = $_GET['num2'];
$operator = $_GET['operator'];
switch ($operator) {
case "None":
echo "You need to set a method!";
break;
case 'Add':
echo "The answer is: ".$num1 + $num2;
break;
case 'Subtract':
echo "The answer is: ".$num1 - $num2;
break;
case 'Multiply':
echo "The answer is: ".$num1 * $num2;
break;
case 'Divide':
echo "The answer is: ".$num1 / $num2;
break;
}
}
?>
</body>
</html>
https://www.php.net/manual/en/language.operators.precedence.php
The . in your string concatenation has a higher operator precedence than your -. You should add parentheses around your $num expressions.
switch ($operator) {
case "None":
echo "You need to set a method!";
break;
case 'Add':
echo "The answer is: ".($num1 + $num2);
break;
case 'Subtract':
echo "The answer is: ". ($num1 - $num2);
break;
case 'Multiply':
echo "The answer is: ".($num1 * $num2);
break;
case 'Divide':
echo "The answer is: ".($num1 / $num2);
break;
}

PHP Q: Variables in <?php ?> not accessible in if/else

So, I'm building a simple program that requires the user input a number which is then posted and generated into several random similar numbers.
The program then requires the user choose the correct variable, which would then be validated by the program.
I'm having issues with what I think is a variable not being 'available' for lack of a better word in the if/else statement.
I feel like I'm making a really simple/stupid mistake.
<?php
$numb = $_GET["number"];
switch ($numb) {
case 1:
echo "1x<br>";
$ans = 1; $n1 = rand(($ans - 5), ($ans + 5)); $n2 = rand(($ans - 5), ($ans + 5)); $n3 = 1; $n4 = rand(($ans - 5), ($ans + 5));
break;
case 2:
echo "2";
break;
case 3:
echo "3";
break;
} echo $ans;
if(isset($_POST['submit']))
{
$rb = $_POST['radio'];
if($rb == $ans){echo "test";}
else{echo "fail";}
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<input type="radio" name="radio" value="<?php echo $n1; ?>"><?php echo $n1 ?>
<input type="radio" name="radio" value="<?php echo $n2; ?>"><?php echo $n2 ?>
<input type="radio" name="radio" value="<?php echo $n3; ?>"><?php echo $n3 ?>
<input type="radio" name="radio" value="<?php echo $n4; ?>"><?php echo $n4 ?>
<input type="submit" name="submit" value="submit" />
</form>
You have to define the variables before useing them in the switch/case.
// Check if get is used
if (isset($_GET['number'])){
$numb = $_GET["number"];
// predefine Variables here
$ans = '';
$n1 = '';
$n2 = '';
$n3 = '';
$n4 = '';
switch ($numb)
{
case 1:
echo "1x<br>";
$ans = 1;
$n1 = rand(($ans - 5), ($ans + 5));
$n2 = rand(($ans - 5), ($ans + 5));
$n3 = 1;
$n4 = rand(($ans - 5), ($ans + 5));
break;
case 2:
echo "2";
break;
case 3:
echo "3";
break;
}
echo $ans;
if (isset($_POST['submit']))
{
$rb = $_POST['radio'];
if ($rb == $ans)
{
echo "test";
}
else
{
echo "fail";
}
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<input type="radio" name="radio" value="<?php echo $n1; ?>"><?php echo $n1 ?>
<input type="radio" name="radio" value="<?php echo $n2; ?>"><?php echo $n2 ?>
<input type="radio" name="radio" value="<?php echo $n3; ?>"><?php echo $n3 ?>
<input type="radio" name="radio" value="<?php echo $n4; ?>"><?php echo $n4 ?>
<input type="submit" name="submit" value="submit"/>
</form>
<?php
} else {
echo "Number not set in get!";
}
You have to use $global variable.
PHP Variables Manual
<?php
$numb = $_GET["number"];
$ans = 0;
switch ($numb) {
case 1:
echo "1x<br>";
$ans = 1;
$n1 = rand(($ans - 5), ($ans + 5));
$n2 = rand(($ans - 5), ($ans + 5));
$n3 = 1;
$n4 = rand(($ans - 5), ($ans + 5));
break;
case 2:
echo "2";
break;
case 3:
echo "3";
break;
} echo 'Answer : [' . $ans . ']<br>';
if(isset($_POST['submit']))
{
$rb = $_POST['radio'];
echo 'PostAnswer : [' . $ans . ']<br>';
if($rb == $ans)
{
echo "Good!";
}
else
{
echo "Bad!";
}
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>?number=1" method="POST">
<input type="radio" name="radio" value="<?php echo $n1 ?>"><?php echo $n1 ?>
<input type="radio" name="radio" value="<?php echo $n2 ?>"><?php echo $n2 ?>
<input type="radio" name="radio" value="<?php echo $n3 ?>"><?php echo $n3 ?>
<input type="radio" name="radio" value="<?php echo $n4 ?>"><?php echo $n4 ?>
<input type="submit" name="submit" value="submit" />
</form>
Your page will change after pressing submit button.
ex:) url_php = test.php request parameter : ?number=1
1) inputing /test.php?number=1
2) $ans = 1
3) After pressing submit button
4) $ans = ""
Like that! You have to maintain ?number=1 or fix it!

PHP Calculator that will continuously compute

The only remaining issue is that when I try and complete a second computation using the value from the previous calculation as the beginning value, the answer is always 0. What else needs to be done in order to just continuously compute equations?
<html>
<?php
session_start();
$_SESSION['num1']= 0;
$num1 = $_SESSION['num1'];
if(isset($_POST['num1'])){
$num1 = $_POST['num1'];
}
if(isset($_POST['num2'])){
$num2 = $_POST['num2'];
}
if(isset($_POST['calcu'])){
$calcu = $_POST['calcu'];
}
function calculate($n1,$n2,$calcu){
switch($calcu)
{
case "Addition":
$compute = $n1 + $n2;
break;
case "Subtraction":
$compute = $n1 - $n2;
break;
case "Multiplication":
$compute = $n1 * $n2;
break;
case "Division":
$compute = $n1 / $n2;
break;
}
return $compute;
}
// echo "$calcu <br /> <br /> Beginning Number: $num1 <br /> Next Number: $num2 <br /><br />";
echo "Answer is:" .calculate($num1,$num2, $calcu);
$_SESSION['num1']=calculate($num1, $num2, $calcu);
?>
<body>
<form action=<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?> method="post">
Beginning Number:<?php echo $_SESSION['num1'];?><br>
Next Number: <input type="number"name="num2"><br>
Calculation: Please type one of the following- Addition, Subtraction, Multiplication, or Division. <input type="text" name="calcu"><br>
<input type="submit"><br>
</form>
</body>
</html>
From your code:
$_SESSION['num1']= 0;
$num1 = $_SESSION['num1'];
Since you've just assigned 0 to $_SESSION['num1'], $num1 will always end up zero as well.
You probably want to wrap that first assignment in a conditional:
if (!isset($_SESSION['num1'])) {
$_SESSION['num1'] = 0;
}

PHP Calculator: My solutions won't show up I click calculate

I've recently started the assignment of building a calculator out of PHP and I can't seem to find what I'm doing wrong in my code. Every time I press calculate it doesn't give me back my solution.
<?php
$num1 = $_GET['num1'];
$num2 = $_GET['num2'];
$cal = $_GET['opt'];
if($num2, $num2 != (int)){
$num1=0;
$num2=0;
}
switch($cal) {
case 'add':
echo $num1+$num2;
break;
case 'sub':
echo $num1-$num2;
break;
case 'mul':
echo $num1*$num2;
break;
case 'div':
echo $num1/$num2;
break;
default:
echo "Invalid Operator";
}
?>
Here is the HTML
<form action="calculate.php" method="GET"/>
Number 1:<input type="text" name="num1"/>
<br />
<select>
<option type="text" name="opt" value="add"> + </option>
<option type="text" name="opt" value="sub"> - </option>
<option type="text" name="opt" value="mul"> * </option>
<option type="text" name="opt" value="div"> / </option>
</select>
<br />
Number 2:<input type="text" name="num2"/>
<br />
<input type="submit" value="calculate"/>
</form>
if($num2, $num2 != (int)) looks like a syntax error to me (the comma).
You just say it doesn't work, are you getting an error message? Have you made sure error reporting is on and displaying errors to your browser? I think it should tell you about the syntax error.
try :
$num1 = intval($_GET['num1']);
$num2 = intval($_GET['num2']);
and remove
if($num2, $num2 != (int)){
$num1=0;
$num2=0;
}
I would initialise the var differently:
<?php
$num1 = $num2 = 0;
if (isset($_GET['num1']) && isset($_GET['num1']) && isset($_GET['num1']))
{
$num1 = $_GET['num1'];
$num2 = $_GET['num2'];
// edit: added validation
if (!is_numeric($num1) || !is_numeric($num2))
{
$res = NULL;
}
else
{
$cal = $_GET['opt'];
switch($cal)
{
case 'add':
$res = $num1+$num2;
break;
case 'sub':
$res = $num1-$num2;
break;
case 'mul':
$res = $num1*$num2;
break;
case 'div':
$res = $num1/$num2;
break;
default:
$res = NULL;
}
}
}
// display html on the same file
?>
<html>
<body>
<form action="calculate.php" method="GET"/>
Number 1:<input type="text" name="num1"/>
<br />
<select>
<option type="text" name="opt" value="add"> + </option>
<option type="text" name="opt" value="sub"> - </option>
<option type="text" name="opt" value="mul"> * </option>
<option type="text" name="opt" value="div"> / </option>
</select>
<br />
Number 2:<input type="text" name="num2"/>
<br />
<input type="submit" value="calculate"/>
</form>
<? if (isset($res) && $res != NULL): ?>
<span class="result-label">Result:</span> <span class="result"><?=$res?></span>
<? endif ?>
</body>
</html>
This is wrong
if($num2, $num2 != (int)){
$num1=0;
$num2=0;
}
try
$num1 = intval( $num1 );
$num2 = intval( $num2 );

Categories