Php – Store plus and minus in a variable PHP

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?

Best Answer

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);