Page 1 of 1

basic function and get

Posted: Tue Dec 14, 2010 3:59 am
by whkowiak
hey there

I am a beginner and I cannot figure out why this basic thing doesn´t work (it try to create a basic calculator as to practice the GET statement, the use of functions and of other statements such a switch).
I first thought about the operation signs (for the op variable) that should be converted (%2F etc) or even wirtten in plain text (like plus, minus etc) but it didn´t change anything. I tried to simplify it also without success. It seems to be that the switch statement is breaking the thing as when I have it, nothing works.
I know it is basic but as a beginner, I am only facing a blank page which only tells me that I made a mistake (are there actually any tools to troubleshoot our code?).
So here is the code:

<html>
<body>
<form action='php.php' method='GET'>
Enter the first number:&nbsp;
<input type='text' name='numb1'><br>
Enter the second number:&nbsp;
<input type='text' name='numb2'><br>
Choose the operation (+, -, *, /)&nbsp;
<input type='text' name='op'><br>
<input type='submit' value='Calculate!'>
</form><br><br>

<?php

$num1 = $_GET['numb1'];
$num2 = $_GET['numb2'];
$op = $_GET['op'];

if ($num1 && $num2 && $op)
{
switch($op)
{
case "+":
$total = $num1 + $num2;
return $total;
break;

case "-":
$total = $num1 - $num2;
return $total;
break;

case "*":
$total = $num1 * $num2;
return $total;
break;

case "/":
$total = $num1 / $num2;
return $total;
break;

default:
echo "Unknown operation";
}
}
echo $total;

?>
</body>
</html>

Thank you very much in advance

Re: basic function and get

Posted: Tue Dec 14, 2010 4:37 am
by social_experiment
Remove all the return $total lines from the switch statement.

Re: basic function and get

Posted: Tue Dec 14, 2010 7:07 am
by whkowiak
@social_experiment: thank you very much for this
Could you explain me why is such thing happening?
When I learned the switch statement, I had a standalone example with the return component and it worked well
is it that it doesn´t goes together with the GET or does it come from the fact that it creates a redundancy when the variable is echoed at the end of the script?

Re: basic function and get

Posted: Tue Dec 14, 2010 7:40 am
by social_experiment
whkowiak wrote:is it that it doesn´t goes together with the GET or does it come from the fact that it creates a redundancy when the variable is echoed at the end of the script?
Honestly i have no idea, i just tinkered with your script :) . I think the return() stops the case 'statements' from being completed and that seems to be the problem but i might almost certainly be wrong.

Re: basic function and get

Posted: Tue Dec 14, 2010 8:10 am
by whkowiak
ok thank you anyway
it was fast and now the script iis working like a charm :)