Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store plus and minus in a variable PHP

Tags:

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?

like image 682
Daniel Avatar asked Mar 27 '26 10:03

Daniel


2 Answers

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);
like image 100
Gazler Avatar answered Mar 29 '26 02:03

Gazler


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)

like image 42
Pascal MARTIN Avatar answered Mar 29 '26 01:03

Pascal MARTIN