Calculator help

So I’ve been teaching myself php little by little and I tried to make a calculator. Now, I got the calculations correct however when I enter the numbers and click submit it shows the sum, difference, product, and quotient. I want to know how to tell it to only show one if that is chosen.

Php Code:[php]<?php

if ($_POST[‘submit_calc’ && ‘option1’]) {
$a=$_POST[‘1’];
$b=$_POST[‘2’];

	$sum=$a+$b;
	echo "Sum equals:".$sum."<br />";

}

if ($_POST[‘submit_calc’ && ‘option2’]) {
$a=$_POST[‘1’];
$b=$_POST[‘2’];

	$dif=$a-$b;
	echo "Difference equals:".$dif."<br />";

}

if ($_POST[‘submit_calc’ && ‘option3’]) {
$a=$_POST[‘1’];
$b=$_POST[‘2’];

	$product=$a*$b;
	echo "product equals:".$product."<br />";

}

if ($_POST[‘submit_calc’ && ‘option4’]) {
$a=$_POST[‘1’];
$b=$_POST[‘2’];

	$quotient=$a/$b;
	echo "quotient equals:".$quotient;

}

?>[/php]

Try this using “Else if”. That way it will show one section, else if that is not the one selected, try the next one etc.

[php]<?php

if ($_POST[‘submit_calc’ && ‘option1’]) {
$a=$_POST[‘1’];
$b=$_POST[‘2’];

	$sum=$a+$b;
	echo "Sum equals:".$sum."<br />";

}elseif ($_POST[‘submit_calc’ && ‘option2’]) {
$a=$_POST[‘1’];
$b=$_POST[‘2’];

	$dif=$a-$b;
	echo "Difference equals:".$dif."<br />";

}elseif ($_POST[‘submit_calc’ && ‘option3’]) {
$a=$_POST[‘1’];
$b=$_POST[‘2’];

	$product=$a*$b;
	echo "product equals:".$product."<br />";

}elseif ($_POST[‘submit_calc’ && ‘option4’]) {
$a=$_POST[‘1’];
$b=$_POST[‘2’];

	$quotient=$a/$b;
	echo "quotient equals:".$quotient;

}?>[/php]

It already knows when the button is pushed, no need to asking it the same question over and over, same with giving it $a and $b every time, just put it once. You’re variables are listed wrong too in the if statements. if ($_POST[‘submit_calc’ && ‘option3’]) { will give out an error message because in submit_calc you’re missing the last ] and after the && you’re missing the $_POST[ at the beginning. What i put below should fix those errors.
[php]
if(isset($_POST[‘submit_calc’])) {
$a=$_POST[‘1’];
$b=$_POST[‘2’];
if($_POST[‘option1’]) {
$sum=$a+$b;
echo “Sum equals:”.$sum."
";
}
if ($_POST[‘option2’]) {
$dif=$a-$b;
echo “Difference equals:”.$dif."
";
}
if ($_POST[‘option3’]) {
$product=$a*$b;
echo “product equals:”.$product."
";
}
if ($_POST[‘option4’]) {
$quotient=$a/$b;
echo “quotient equals:”.$quotient;
}
}
?>[/php]

Sponsor our Newsletter | Privacy Policy | Terms of Service