Exchange elseif code for switch case

I'm having trouble changing a code I made in else if to switch case. I'm not getting the code to work, it gets values and operation by $_GET and does the selected operation:

I leave the code here:

if((!is_numeric($num1) || $num1 == '' || $num1 == '0') && $operator == '/') 
    echo "ERRO: Numero 1 inserido e' zero";
else if((!is_numeric($num2) || $num2 == '' || $num2 == '0') && $operator == '/') 
    echo "ERRO: Numero 2 inserido e' zero";
else {
   //se a divisao for feita por zero, da mensagem de erro informando que o valor inserido foi zero
    if( !empty($operator) ) {
        if($operator == '+')
            $result = $num1 + $num2;
        else if($operator == '-')
            $result = $num1 - $num2;
        else if($operator == '*')
            $result = $num1*$num2;
        else
            $result = $num1/$num2;
        echo "O resultado é: ".$result;
   }
}
Author: Maniero, 2016-07-07

2 answers

Would need to improve a lot, but basically it would be this:

if (!is_numeric($num1) || !is_numeric($num2) {
    echo "ERRO: as entradas precisam ser numéricas";
    //encerra de alguma forma, dpende do código.
}
$num1 = intval($num1); //pode  ser um floatval
$num2 = intval($num2);
switch ($operator) {
    case '+':
        $result = $num1 + $num2;
        break;
    case '-':
        $result = $num1 - $num2;
        break;
    case '*':
        $result = $num1 * $num2;
        break;
    case '/':
        if ($num2 == 0) {
            echo "ERRO: Não pode fazer divisão por zero";
            break;
        }
        $result = $num1 / $num2;
        break;
    default:
        //talvez mereça alguma mensagem de erro se não for nenhum operador válido
}
echo "O resultado é: " . $result;

I put on GitHub for future reference .

Do not convert to switch what if works best, do this only with the choice of operators.

Do not forget to convert the values that are as text to numeric to make the account properly.

The test if it is numeric is a bit naive.

The test if the value of the divisor is 0 only needs to be done if the operator is split, then put it there. And the dividend can be 0.

Has several other things that could be done better.

Perhaps the difficulty is because it was not separating each responsibility. It's one thing to check that the data is within the minimum standards to do something useful, another thing and select what to do. I don't think it pays to check the conditional value separately (case of division by 0).

Need to see if you want only integers or also decimal values. It has a number of other decisions to make good code for use. If it was a basic exercise then it would have been better to at least try to do what you want.

 4
Author: Maniero, 2020-02-05 20:03:37

You can try like this:

    $num1 = $_GET['num1']; 
    $operator = $_GET['operator']; 
    $num2 = $_GET['num2']; 

    switch (true) {
    case !is_numeric($num1) && $operator == '/':
    case $num1 == '' && $operator == '/':
    case $num1 == '0' && $operator == '/':
        echo "ERRO: Numero 1 inserido e' zero";
        break;

    case !is_numeric($num2) && $operator == '/':
    case $num2 == '' && $operator == '/':
    case $num2 == '0' && $operator == '/':
        echo "ERRO: Numero 2 inserido e' zero";
        break;
    default:
        switch ($operator) {
            case '+':
                $result = $num1 + $num2;
                break;
            case '-':
                $result = $num1 - $num2;
                break;
            case '*':
                $result = $num1 * $num2;
                break;
            case '/':
                $result = $num1 / $num2;
                break;
        }
        echo "O resultado é: ".$result;
    }
 2
Author: Ricardo Mota, 2016-11-14 11:23:34