在变量PHP中存储加号和减号

How can I solve this problem:

if ($variable == 1) {
    $math = "-";
} else {
    $math = "+";
}

$numberOne = 10;
$numberTwo = 10;

$result = $numberOne $math $numberTwo;

This doesn´t work, is there any way to solve this?

This will work for your example. A subtraction is the same as adding a negative. This will be far safer than the alternative of using eval.

if ($variable == 1) {
    $modifier = -1;
} else {
    $modifier = 1;
}

$numberOne = 10;
$numberTwo = 10;

$result = $numberOne + ($numberTwo * $modifier);
if ($variable == 1) {
    $math = -1; // subtraction
} else {
    $math = 1; // addition
}

$numberOne = 10;
$numberTwo = 10;

$result = $numberOne + ($math * $numberTwo);

I suppose you could use eval() -- but that would be quite a bad idea (it would not be good for performances, it's not "clean", ...)


In this kind of situation, I would generally go with a switch on the operator, and one case per possible operator.

Here, it would mean using something like this :

switch ($math) {
    case '+':
        $result = $numberOne + $numberTwo;
        break;
    case '-':
        $result = $numberOne - $numberTwo;
        break;
}

Which can easily be extends to other operators.


(In your specific situation, if you only have + and -, though, some calculation based on a multiplication by +1 or -1 would be faster to write)

No love for the ternary operator?
To minify Gazler's answer a bit further:

$modifier = ($variable == 1) : -1 ? 1;

$numberOne = 10;
$numberTwo = 10;

$result = $numberOne + ($numberTwo*$modifier);

If you plan to use more complex mathematics, you can use the eval() function.