0

I have + sign as string and I would like to use it as operator for 2 numbers.

Example:

$n1 = 1;
$n2 = 2;
$plus = '+';

echo $n1 . $plus . $n2;

The previous example would print 1 + 2, I want to print 3 instead.

I tried to search for a function that could convert the plus string or encode/decode it, But couldn't find a solution.

Also I tried:

echo $n1 + $plus + $n2;

But got this error: WARNING A non-numeric value encountered

Is that possible?

markoo
  • 1
  • 2
    You're are looking for [`eval()`](https://www.php.net/manual/en/function.eval.php). But use it with caution. – Sven Eberth Jul 04 '21 at 19:34
  • @markoo: take a search on site. there are a couple of questions that point into the direction and some of them have really good answers worth the search. asking this question again normally will not give you good comments nor answers. just the quick, half baked kind normally. you're looking for _"evaluating a mathematical expression"_ or something along the lines. and if you look into eval, search about it as well. e.g. "is eval evil" to get a bit of an impression. – hakre Jul 04 '21 at 20:13

0 Answers0