-3

please help me this code, when i click button, it shows

Notice: Undefined variable: result in C:\xampp\htdocs\tinhtong_luatoantu.php on line 47
<?php 
    $nhapso1 = isset($_GET['so1']) ? $_GET['so1'] : '-1';
    $nhapso2 = isset($_GET['so2']) ? $_GET['so2'] : '-1';
    $pheptinh = $_GET['toantu'];
    if ($nhapso1 < 0 || $nhapso2 < 0) {
        echo 'Vui lòng nhập vào toán hạng & chọn toán tử';
    }
    else {
        switch($pheptinh) {
            case '------':
                echo 'Vui lòng nhập vào toán hạng & chọn toán tử';
                break;
            case '+':
                $result = $nhapso1 + $nhapso2;
                break;
            case '-':
                $result = $nhapso1 - $nhapso2;
                break;
            case '*':
                $result = $nhapso1 * $nhapso2;
                break;
            case '/':
                $result = $nhapso1 / $nhapso2;
                break;
            default:
                echo '';
                break;
        }
        echo round($result, 2);
    }
?>
vvvvv
  • 25,404
  • 19
  • 49
  • 81
ThiHuu
  • 9
  • 2
  • 2
    Does this answer your question? [Undefined Variable PHP Error](https://stackoverflow.com/questions/12219977/undefined-variable-php-error) – Kunal Raut Jul 11 '20 at 04:35
  • Not seeing/counting a Line 47. – GetSet Jul 11 '20 at 05:03
  • You are defining $result only in some cases. You can initialize it before switch begin: $result = 0; or assign some value to it in each case. – mnesarco Jul 11 '20 at 15:37

2 Answers2

0

In switch cases when your argument doesn't match with the given value it runs default case. In your code, when running the default case there is no declared $result variable which you echo at the end of the code. You should set the default value for $result either beginning of the code or default case. Simply say PHP compiler doesn't run codes that have in fail cases. So there is no $result when running default statement in switch case.

-1

That's because if the first case of the switch statement gets executed you are not defining $result variable and the same is with the default case. To avoid this, you can initialise the result variable with a default value (let's say 0) before your switch statement starts

Tushar
  • 665
  • 5
  • 11