0

I am programming in php and I have the following variable :

$calculation = '15-12';

Is there a function allowing me to convert the character string into calculation?

cladev
  • 11
  • 4
  • You have `eval`, but [be careful around using it](https://stackoverflow.com/questions/3499672/when-if-ever-is-eval-not-evil). – El_Vanja Apr 08 '21 at 15:06

4 Answers4

1

Yeah, you can use eval expression for such case, but it's not recommended (mention by @El_Vanja). It would be better to cast the values to their correct types and do the calculation.

eval scenario

$calculation = '15-12';
$result = eval('return '.$calculation.';');
print $result; // output will be 3

casted types

$calculation = '15-12';

$values = explode('-', $calculation);

$result = intval($values[0]) - intval($values[1]);

print $result;
aspirinemaga
  • 3,753
  • 10
  • 52
  • 95
0

The eval() function could be used here:

$calculation = '15-12';
$result = eval('return '.$calculation.';');

echo $result; //outputs '3'
cOle2
  • 4,725
  • 1
  • 24
  • 26
0

You can use eval() https://www.php.net/manual/en/function.eval

Pay attention that this function execute the string like PHP code and if it contains specific mathematical expression, it will fail. In this case you'll need to parse your string and do calculation by yourself or use an external library.

Ichinator
  • 357
  • 2
  • 11
0

@aspirinemaga's solution for casting is the approach that I would take.

If it isn't always going to be subtraction (and you want to avoid using eval()) then you could always use strpos to figure out if it is adding/subtracting/multiplying and then pass it the expression to a switch statement to get your calc.