How do I return a valid result from an operation in PHP?

0

Hello.

I want to return the result of an operation using two numbers and the operator as the 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 example above, it returns the operation, not the result. Example: "3 + 2" not "5".

    
asked by anonymous 04.10.2016 / 19:54

1 answer

4

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

I'll clarify an example, the division operation causes error when it tries to divide by zero.

But this does not happen when you multiply, subtract, or sum.

So when writing a generic function to encompass these four operators, you would have to create conditionals to check when you are trying to divide and care for zero.

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;
    }
}
    
04.10.2016 / 20:12