Reputation: 241
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?
Upvotes: 3
Views: 13465
Reputation: 28187
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);
Upvotes: 1
Reputation: 376
If you plan to use more complex mathematics, you can use the eval()
function.
Upvotes: 0
Reputation: 401152
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)
Upvotes: 3
Reputation: 4039
if ($variable == 1) {
$math = -1; // subtraction
} else {
$math = 1; // addition
}
$numberOne = 10;
$numberTwo = 10;
$result = $numberOne + ($math * $numberTwo);
Upvotes: 2
Reputation: 84180
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);
Upvotes: 11