0

I'm kinda new to this but I was wondering if it is possible to add some dynamic calculation into a function as a parameter.

The thing is inside my function I am formatting stuff in a consistent way but each time I want to add a certain different calculation into the parameter.

<?php
function dynamicCalculator($calculation){

 $result = $calculation;

 //some formatting
 return $result;
}

 echo dynamicCalculator('(3x5)+1');

This doesn't work of course but if anyone has an idea how this could work I would love to hear it.

greatwolf
  • 19,633
  • 13
  • 69
  • 104

4 Answers4

1

Your looking for RPN (Reverse Polish Notation)

Here is one example

http://pear.php.net/package/Math_RPN/

which would allow you to use

$expression = "(2^3)+sin(30)-(!4)+(3/4)";

$rpn = new Math_Rpn(); echo $rpn->calculate($expression,'deg',false);

And not have to use Eval

exussum
  • 17,675
  • 8
  • 30
  • 64
1

What you are looking for is the eval function.

eval('$result = (3*5)+1');

But beware to make sure you're not passing possibly harmful code to that function.

Kermit
  • 33,206
  • 11
  • 83
  • 119
Odie
  • 63
  • 5
0

Use eval. eval("10+2") should return 12. Be careful though, you can also run PHP code with eval.

Someone else had a similar question on StackOverflow.

Community
  • 1
  • 1
sheng
  • 1,207
  • 8
  • 15
0

You could use this:

function dynamicCalculator($calculation) {
   $result = eval($calculation);
   return $result;
}
Annabel
  • 1,354
  • 14
  • 23
  • 2
    Note: in the documentation http://php.net/manual/en/function.eval.php it mentions this is dangerous as all sorts of PHP code could be smuggled into `$calculation`. – Annabel Oct 13 '13 at 21:53