0

I have 3 variables :

$a = 5;
$b = 3
$o = "*";

The $o variable contains a string value. This value can also be "/", "+", "-".

So when I concatenate $a.$o.$b :

$result = $a.$o.$b;

echo $result;

The result is 5*3 (a string) instead of 15.

So how to convert operator string into real operator ?

3
  • 3
    switch($o) {case '+': $result = $a + $b; break; case '-': $result = $a - $b; break; case '*': $result = $a * $b; break; case '/': $result = $a / $b; break; } Commented Feb 12, 2016 at 15:25
  • 1
    Hi Mark Baker, thank you for phpexcel, I use it ! Commented Feb 12, 2016 at 15:28
  • 3
    Possible duplicate of PHP use string as operator Commented Feb 12, 2016 at 15:32

5 Answers 5

1

You can't, you'd need to make a function or a switch statement to check each of the operators.

Read this question and its answers so you'll understand how to do it.

Sign up to request clarification or add additional context in comments.

Comments

1

Simple, short and save solution:

$a = 5;
$b = 3
$o = "*";

$simplecalc = function($a,$b,$op) {
 switch($op):
  case "*":
  return $a*$b;
 case "+":
  return $a+$b;
 case "-":
  return $a-$b;
 case "/";
  return $a/$b;
 default:
  return false;
 endswitch;
};

$result = $simplecalc($a,$b,$o);

Comments

0

Actually you can do it, by using eval. But it hurts to recommend using eval, so I just give you a link to another question with a good answer: calculate math expression from a string using eval

1 Comment

Thank you, I think I can use eval securely because the three variables don't come from user input.
0

You can use eval. For example:

eval('echo 5*3;')

will echo the number 15.

Comments

0

I believe this is what you are looking for.

$a = 5;
$b = 3;
$o = "*";
$result =  eval( "echo $a$o$b;" );  
echo $result; 

Please note that using eval() is very dangerous, because it allows execution of arbitrary PHP code.

1 Comment

$result = eval("return ".$a.$o.$b.";");

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.