3

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?

Daniel
  • 241
  • 3
  • 4
  • 10
  • You cannot just put variables in a row and expect them to be evaluated as PHP expression. – Felix Kling Jul 20 '11 at 21:00
  • Similar to http://stackoverflow.com/questions/1015242/how-to-evaluate-formula-passed-as-string-in-php. Ought to be helpful if you plan on supporting other operations. – simshaun Jul 20 '11 at 21:02
  • @Gazler's answer works, but what you're trying to do here suggests something of a misunderstanding of how PHP interprets statements (you're assuming it will concatenate the values of three variables and then correctly evaluate them as a mathematical statement). Is there a more-basic question we can answer about why this doesn't work? – Dan J Jul 20 '11 at 21:02

5 Answers5

11

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);
Gazler
  • 83,029
  • 18
  • 279
  • 245
3

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)

Pascal MARTIN
  • 395,085
  • 80
  • 655
  • 663
2
if ($variable == 1) {
    $math = -1; // subtraction
} else {
    $math = 1; // addition
}

$numberOne = 10;
$numberTwo = 10;

$result = $numberOne + ($math * $numberTwo);
Paul DelRe
  • 4,003
  • 1
  • 24
  • 26
1

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);
Community
  • 1
  • 1
barfoon
  • 27,481
  • 26
  • 92
  • 138
  • 1
    I think most people avoid answers using the ternary operator unless the code provided uses it for clarity reasons. There is absolutely nothing wrong with it though, and I would use it if I was using my own solution. – Gazler Jul 20 '11 at 21:06
  • 1
    minify hell: `$result = $numberOne + ($numberTwo * (($variable == 1) : -1 ? 1) );` – feeela Jul 20 '11 at 21:12
0

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

Maxime Fafard
  • 370
  • 2
  • 8