Hi, I'm new to programming. I'm trying to do the basic operations using a radio button, but addition and subtraction don't work for me. I don't understand why.
<form method="POST" action="resultado.php">
<table>
<tr>
<th>Numreo 1</th>
<td>
<input type="text" name="n1"></input>
</td>
</tr>
<tr>
<th>Numero 2</th>
<td>
<input type="text" name="n2"></input>
</td>
</tr>
<tr>
<td>
<input type="radio" name="operacion" value="suma">Suma</input>
<input type="radio" name="operacion" value="resta">Resta</input>
<input type="radio" name="operacion" value="producto">Multiplicacion</input>
</td>
<td>
<input type="radio" name="operacion" value="division">Division</input>
<input type="radio" name="operacion" value="potencia">Potencia</input>
<input type="radio" name="operacion" value="modulo">Modulo</input>
</td>
</tr>
<tr>
<td></td>
<td>
<input type="submit" name="enviar" value="ENVIAR"></input>
</td>
</tr>
</table>
</form>
//otra pagina
<?php
$n1 = $_POST['n1'];
$n2 = $_POST['n2'];
switch ($_POST['operacion']) {
case 'suma':
echo "el resultado es ".$n1+$n2;
break;
case 'resta':
echo "el resultado es ".$n1-$n2;
break;
case 'producto':
echo "el resultado es ".$n1*$n2;
break;
case 'division':
echo "el resultado es ".$n1/$n2;
break;
case 'modulo':
echo "el resultado es ".$n1%$n2;
break;
case 'potencia':
echo "el resultado es ".pow($n1, $n2);
break;
default:
# code...
break;
}
?>
The problem is in the precedence of operators : the concatenation operator (
.
) has the same precedence as the addition (+
) and subtraction (-
) operators and that is why you do not get the result you expected.Put the operations in parentheses so there are no such precedence issues , and that will fix the problem:
You should at least check that the values arrive before trying to trade them. For example:
Then, always put the mathematical operations in parentheses when you are concatenating with strings to avoid problems and make the code clearer, or better put the result of the operations in a new variable beforehand and then concatenate this one. For example:
When problems arise, simplify and do traces / debug.