adplus-dvertising

Warning: Undefined array key 'name'

Asked 2 days ago
Viewed 10 times
php

Im having a problem doing a math operation in php, returning this error:

Warning: Undefined array key "valor1" in C:\xampp\htdocs\provaphp\pages\aula_sobreNos.php on line 17

Warning: Undefined array key "valor2" in C:\xampp\htdocs\provaphp\pages\aula_sobreNos.php on line 18

Warning: Undefined array key "operador1" in C:\xampp\htdocs\provaphp\pages\aula_sobreNos.php on line 19

This is the code:

 <form method="get">
    <input type="hidden" name="p" value="sobreNos">
    <input type="number" name="valor1">
    <input type="text" name="operador1">
    <input type="number" name="valor2">        
    <input type="submit">
</form>

php part:

 $valor1 = $_GET["valor1"];
$valor2 = $_GET["valor2"];
$operador1 = $_GET["operador1"];

$resultado = mathOp($operador1, $valor1, $valor2);
echo $resultado;

function mathOp($operador1, $valor1, $valor2) {
    switch($operador1) {
        case '+':
            return($valor1 + $valor2);
        case '-':
            return($valor1 - $valor2);
        case '*':
            return($valor1 * $valor2);
        case '/':
            if($valor2 == 0) {
                return 'Não pode ser dividido por 0!';
            } else {
                return($valor1 / $valor2);
            }
    }
}

Thanks for your responses!

asked 2 days ago

Correct Answer

If the system cannot find the correct value for assigning to a variable, then it will prompt warnings like Undefined xxxx "variable_name" in xxxxx

Hence, please use isset to check whether the values exist so that it is assignable to a variable

So, change

$valor1 = $_GET["valor1"];
$valor2 = $_GET["valor2"];
$operador1 = $_GET["operador1"];

to

if (isset($_GET["valor1"])){
$valor1 = $_GET["valor1"];
}

if (isset($_GET["valor2"])){
$valor2 = $_GET["valor2"];
}

if (isset($_GET["operador1"])){
$operador1 = $_GET["operador1"];
}
answered 2 days ago