-2

can we use math formula from other variable/database? example:

var x = 7;
var formula = '+';
var y = 10;

I mean that variables will output = 17 (7 + 10);

but how to implement this formula using Javascript/PHP?

IRvanFauziE
  • 823
  • 11
  • 16
  • @hakre: how about javascript version? – IRvanFauziE Sep 25 '13 at 06:54
  • Please use the search. Also if you look for javascript, you should not tag as PHP. - possible duplicate of: [Safe evaluation of arithmetic expressions in Javascript](http://stackoverflow.com/q/5066824/367456) – hakre Sep 25 '13 at 07:26

5 Answers5

1

For your example you could do this:

var x = 7;
var formula = '+';
var y = 10;
z = eval(x+formula+y);  // 17
document.write(z);

But eval is a big problem for security, and you really shouldn't use it. If you could give more detail on what you're trying to achieve it might be possible to suggest an alternative.

1

PHP Version

use eval() in php to run a php code segment:

<?php
$x = 7;
$formula = '+';
$y = 10;
$expression = '$result = ' .$x . ' ' . $formula . ' ' . $y . ";";
echo $expression, "\n";    // $result = 7 + 10;
eval($expression);         // run the code
echo $result, "\n";        // ouput 17

see the result of the code here

srain
  • 8,944
  • 6
  • 30
  • 42
0

In php you can use as below. You can avoid eval in this way.

$x = 7;
$formula = '+';
$y = 10;

switch ($formula) {

case "+" : $res = $x + $y;
          break;

case "-" : $res = $x - $y;
          break;

.
.
.
.


}

echo $res;
sandy
  • 1,126
  • 1
  • 7
  • 17
0

Something like this should work in PHP and javascript(with a little modification). Also I'd recommend not using eval what so ever because of security reasons.

function math($x, $y, $sign){
    switch($sign){
        case '+':
            return $x + $y;
        case '-':
            return $x - $y;
        case '*':
            return $x * $y;
        case '/':
            return $x / $y;
        default:
            return;
    }
}
$x = 7;
$formula = '+';
$y = 10;
echo math($x, $y, $formula);#returns 17
Class
  • 3,149
  • 3
  • 22
  • 31
0

If you'll be evaluating textual formulas repeatedly with 'eval(),' you may wish to store it within a function - like this:

var formula = "x + y";
var func;
eval("func = function(){return" + formula + "}");

At this point, you could call 'func()' at any time when variables x and y exist within the given scope. For example:

var x = 7;
var y = 10;
var answer = func();

The value of answer would then be '17.'