How to return a valid result from a PHP operation?

Asked

Viewed 94 times

0

Hello.

I want to return the result of an operation using two numbers and the operator as parameter. It turns out that my result is a string.

<?php
$n1 = $_POST['n1']; //primeiro número
$n2 = $_POST['n2']; //segundo número
$operador = $_POST['operador']; // +-*/

$resultado = fazConta($n1,$n2,$operador);
echo $resultado;

function fazConta($n1,$n2,$operador){

    $x = $n1.$operador.$n2; 
    return $x;

}
?>

In the above example, it returns the operation and not the result. Example: "3+2" and not "5".

  • RelatedCalculator in php. Can you do the eval() ex: $op = '+';&#xA;eval("echo 30 $op 5;"); but of a read before in Eval is either good or bad?

  • 1

    Nor would I be able to return 5, for the . is the string concatenation operator.

1 answer

4


You cannot use operators as variables because operators are constructors. It cannot be passed as string or object or anything like that. A single means viable would be the use of eval(). A "smart" and more consistent means is to create a function for each operator. soma() subtrai() multiplica(), divide(). This way it is more organized and does not need to mix specific rules of one operation with another.

Let me make one more clear example, the split operation causes error when it tries to divide by zero.

But this does not occur when multiply, subtract or sum.

So, when writing a generic function to encompass these four operators, you would have to create conditionals to verify when you’re trying to divide and take care of the zero value.

function carculadera($operador, $n1, $n2) {
    switch($operador) {
        case '+':
            return $n1 + $n2;
        break;
        case '-':
            return $n1 - $n2;
        break;
        case '/':
            if ($n1 != 0 && $n2 != 0) {
                return $n1 / $n2;
            } else {
                return 0;
            }
        break;
        case '*':
            return $n1 * $n2;
        break;
    }
}

Browser other questions tagged

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