Daniel
Daniel

Reputation: 241

Store plus and minus in a variable 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?

Upvotes: 3

Views: 13465

Answers (5)

barfoon
barfoon

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

Maxime Fafard
Maxime Fafard

Reputation: 376

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

Upvotes: 0

Pascal MARTIN
Pascal MARTIN

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

Paul DelRe
Paul DelRe

Reputation: 4039

if ($variable == 1) {
    $math = -1; // subtraction
} else {
    $math = 1; // addition
}

$numberOne = 10;
$numberTwo = 10;

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

Upvotes: 2

Gazler
Gazler

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

Related Questions