Store arithmetic operator in variable

4

I have the following code:

$value1 = 10;
$value2 = $value1 + 10; // $value2 == 20

I need the + operator to be variable, ie in my case I need to be + or - .

I've tried the obvious but it sure would not work, here's the code below:

$operator = "+";
$value1 = 10;
$value2 = $value1 . $operator . 10;

Is it possible to accomplish something close to what I'm trying to do?

Important: The variable $operator will always receive the value + or - in string format.

    
asked by anonymous 13.11.2015 / 14:34

5 answers

10

There are several ways to do this, but it is best not to invent, to do the obvious using a comparison. Example:

$operator = "+";
$value1 = 10;
switch ($operator) {
    case "+":
        $value2 = $value1 + 10;
        break;
    case "-":
        $value2 = $value1 - 10;
        break;
}

You have other interesting examples in other answers.

    
13.11.2015 / 14:37
7

I do not understand why, but you can also use this method for online options:

<?php

$operar = [
    '+' => function($a, $b) { return $a + $b; },
    '%' => function($a, $b) { return $a % $b; },
    '*' => function($a, $b) { return $a * $b; },
    '-' => function($a, $b) { return $a - $b; }
];

$sinal = '+';

print $operar[$sinal](10,10); # (int) 20
print $operar['+'](10,10); # (int) 20

?>

You can still use the switch control structure as done in the other response, however they are both functional.

    
13.11.2015 / 15:13
3

I would implement it as follows:

$value1 = 10;
$operador = '+';
$value2 = ($operador === '+') ? 10 : -10;

$value2 = $value1 + $value2;

or

$value1 = 10;
$value2 = 10;
$operador = '+';
if($operador == '-'){
    $value2 *= -1;
}

$value2 = $value1 + $value2;
    
13.11.2015 / 14:47
2

Another way to implement this is by using BC Math Functions and call_user_func , example:

/*
* bcadd = adição
* bcsub = subtração
* bcmul = multiplicação
* bcdiv = divisão
*/
$operador = 'add';
$val1 = 10;
$val2 = 10;
$result = call_user_func('bc'.$operador,$val1,$val2);

IDEONE

    
26.07.2016 / 18:05
0

You could also do this using Object Orientation, where all complexity is the responsibility of the class Calculator to solve, thus making it much easier to use, both when maintaining future code.

<?php

class Calculator {

  private $operator;
  private $result;

  public function __construct($value1)
  {
    $this->result = $value1;
  }

  public function calculate($operator, $value1)
  {

    switch ($operator) {
      case '+':
        $this->result += $value1;
        break;
      case '-':
        $this->result -= $value1;
        break;
      case '/':
        $this->result /= $value1;
        break;
      case '*':
        $this->result *= $value1;
        break;
      case '%':
        $this->result %= $value1;
        break;
    }

    return $this;

  }

  public function getResult()
  {
    return $this->result;
  }

}

Calculate class usage test:

<?php

require_once 'Calculator.php';

$calc = new Calculator(10);
echo $calc->calculate('+', 10)
->calculate('+', 10)
->getResult();//30

echo '<br>';
$calc1 = new Calculator(100);
echo $calc1->calculate('-', 10)->getResult();//90

echo '<br>';

$calc2 = new Calculator(2);
echo $calc2->calculate('*', 2)
->calculate('*', 2)
->getResult();//8
    
13.11.2015 / 16:41