Swap elseif code for switch case

Asked

Viewed 728 times

0

I’m having trouble modifying a code I made in else if for switch case. I’m not getting the code to work, he 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;
   }
}
  • 1

    Show me what you’ve done with switch. And tell me what problem you found.

  • I haven’t done much yet, I don’t know how to switch case to the first part of ! is_numeric

  • vc need to 'separate' the validation of the input numbers with the choice of operation, the switch will probably be applied only in the choice of operation.

  • I’ll try to answer the question, but only with this piece of code

2 answers

4


It 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 in the Github for future reference.

Don’t convert to the switch what the if works best, do this only with the choice of operators.

Don’t forget to convert the values that are as text to numeric to do the account properly.

The test if it’s numerical is a little naive.

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

There are several other things that could be done better.

Maybe the difficulty is because I wasn’t separating every responsibility. It is one thing to check whether the data is within the minimum standards to do something useful, another thing and select what to do. I don’t think it’s worth checking the conditional value separately (case of division by 0).

You need to see if you want only integers or decimal values as well. There are 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 wish.

  • Thanks for the help! I’m still a beginner in php! hug

  • 3

    +1, especially by warning "Do not convert to switch what if works best, do this only with the choice of operators."

2

You can try it 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;
    }
  • Hello Ricardo, I will try, but it seems to me the most correct way! Thank you :)

  • I tested and worked here Mario. In case you can not post the code for us.

  • Ricardo, it worked in beauty! Thank you so much! I’m learning even php, sorry if the code before had beginner flaws! Hug

  • 5

    switch true was the first time I saw :)

  • 2

    @mustache the worst will be when he tries to use inverted switch in a more serious language and realize that only works in PHP pq is not optimized .

  • 1

    @Ricardomota doesn’t need to put "I hope I’ve helped" on all of his answers. The community recognizes this by the answers you’ve given. Accompanies the meta discussion

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.