Store arithmetic operator in variable

Asked

Viewed 267 times

4

I have the following code:

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

I need the operator + is variable, that is, in my case I need it to be + or -.

I tried the obvious but already sure that would not work, below follows the code:

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

It’s possible to accomplish something close to what I’m trying to do?

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

  • 1

    Some special reason you want to do this ?

  • Not really. It’s just that I’ve come across this situation a few times, and I’ve always used condition to accomplish this task. I wonder if there was something close to the format I quoted in the question.

  • This smells like unnecessary stuff.. rsrs

5 answers

10


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

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

I put in the Github for future reference.

There are other interesting examples in other answers.

  • That’s right, but without a condition to check the string $operator would it be possible?

  • It is possible by using Eval.

  • 2

    @Thyagothysoft would not be without doing a huge gambit and making the code unsafe. There are other ways to write this, but in the background all will use a comparison.

  • 3

    @Rafaelmenabarreto don’t even think about it.

  • 2

    @Rafaelmenabarreto don’t do this.

  • I just answered the question.

  • It would be possible to implement without the need to "test" the string $operator, using project standards. Example: [https://en.wikipedia.org/wiki/Factory_(Object-oriented_programming)#Encapsulation ]

  • @Leonardoleal is possible, but it would probably be an abuse.

Show 3 more comments

7

Conintuo not understanding 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 also use the control structure switch as done in the other answer, either way, are both functional.

  • 2

    In some circumstances I would use it this way.

  • 1

    The strange thing is that I’ve never been forced into any of the forms in so much programming time.

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;
  • I would do as in the first also if it is something simple and fixed always. I gave the switch in order to expand.

  • @bigown In fact if you start working with all operators it is best to do by switch.

  • Really is limited to + and -

2

Another way to implement 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

0

You could also do as follows using object orientation, where all the complexity lies by responsibility of the class Calculator solve, thus making its use much easier, so much so when the future maintenance of the 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;
  }

}

Test of use of class Calculate:

<?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
  • If it is a constructor to perform simple addition and addition calculations, and others, the use of a class is dispensable, a normal function would do the same.

  • A normal function would do the same with method chaining?

  • That is the point, it would not be necessary to chain methods, only 1 function would do everything.

  • Yes, if it is to develop in a structured way a simple function can solve, but in a system oriented objects with MVC architecture for example, it would not be a good practice, which is not the case here.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.