0

Say I had this code below:

$operator = "+";
$num1 = 10;
$num2 = 32;

echo "the sum of " . $num1 . " and " . $num2 . " is " . ($num1.$operator.$num2);

As you can see, I'm trying to use a variable to define the operator by concatenating it. However, when running this code, the operator is displayed as plain text instead of being used to answer the question.

Obviously, I get an output like this: "the sum of 10 and 32 is 10+32"

Surely I'm doing something wrong?

hakre
  • 193,403
  • 52
  • 435
  • 836

1 Answers1

0

Avoid eval as much as possible. But here is the answer to do it with eval:

<?php

$operator = '+';
$num1 = 10;
$num2 = 32;

eval(sprintf('echo %d %s %d;', $num1, $operator, $num2));

Here a little cleaner code

$operator = '+';
$num1 = 10;
$num2 = 32;

switch ($operator) {
    case '+':
        $result = $num1 + $num2;
        break;
    case '-':
        $result = $num1 - $num2;
        break;
    case '*':
        $result = $num1 * $num2;
        break;
    case '/':
        $result = $num1 / $num2;
        break;
    default:
        echo "Invalid operator";
        break;
}

echo 'Result: ' . $result;
CBergau
  • 636
  • 2
  • 10
  • 26