JayGatsby
JayGatsby

Reputation: 1621

Arithmetic operations between variables

I'm beginner with php. I am trying to apply some random arithmetic operation between two variables

$operators = array(
    "+",
    "-",
    "*",
    "/"
    );

$num1 = 10;
$num2 = 5;

$result = $num1 . $operators[array_rand($operators)] . $num2;

echo $result;

it prints values like these

10+5
10-5

How can I edit my code in order to do this arithmetic operation?

Upvotes: 4

Views: 2486

Answers (2)

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324640

While you could use eval() to do this, it relies on the variables being safe.

This is much, much safer:

function compute($num1, $operator, $num2) {
    switch($operator) {
        case "+": return $num1 + $num2;
        case "-": return $num1 - $num2;
        case "*": return $num1 * $num2;
        case "/": return $num1 / $num2;

        // you can define more operators here, and they don't
        // have to keep to PHP syntax. For instance:
        case "^": return pow($num1, $num2);

        // and handle errors:
        default: throw new UnexpectedValueException("Invalid operator");
    }
}

Now you can call:

echo compute($num1, $operators[array_rand($operators)], $num2);

Upvotes: 7

Rizier123
Rizier123

Reputation: 59681

This should work for you!

You can use this function:

function calculate_string( $mathString )    {
    $mathString = trim($mathString);     // trim white spaces
    $mathString = preg_replace ('[^0-9\+-\*\/\(\) ]', '', $mathString);    // remove any non-numbers chars; exception for math operators

    $compute = create_function("", "return (" . $mathString . ");" );
    return 0 + $compute();
}

//As an example
echo calculate_string("10+5");

Output:

15

So in your case you can do this:

$operators = array(
    "+",
    "-",
    "*",
    "/"
    );

$num1 = 10;
$num2 = 5;

echo calculate_string($num1 . $operators[array_rand($operators)] . $num2);

Upvotes: 0

Related Questions