user3882511
user3882511

Reputation: 125

how to use a string as formula for mathematical calculations in php?

There are several mathematical formulas stored in mysql rows for individual usage. i.e. a field contains this formula as a string (varchar): (($a+$b)/$c)

Now in php variables are filled dynamically by an foreach loop:

$temp_array[$deviceData["devicename"]] = $deviceSum;

$deviceData["devicename"] represents $a, $b, $c.

The array can look like $a=>20, $b=>30, $c=>580.

How can i use this variables with the string-formula?

thx for helping.

Upvotes: 1

Views: 963

Answers (1)

Lawrence Cherone
Lawrence Cherone

Reputation: 46620

Unfortunately, you need to eval it.

And if the values are like:

$deviceData["devicename"] = [
    'a' => 20,
    'b' => 30,
    'c' => 580
];

You might want to isolate them as you will need to extract() them out to make use if there is more then 3 etc, encapsulating in function/closure would work.

<?php
$formula = '(($a+$b)/$c)';

$deviceData["devicename"] = ['a' => 20, 'b' => 30, 'c' => 580];

$runFormula = function ($formula, $data) { 
    extract($data); 
    return eval('return '.$formula.';'); 
};

echo $runFormula($formula, $deviceData["devicename"]);

https://3v4l.org/I2rbk

Or just:

extract($deviceData["devicename"]); 
echo eval('return '.$formula.';'); 

But you're polluting your global variable table with whats extracted, potentially causing more issues.

Though dont use eval if the formula is defined by the user, or your will have security issues.


In no respect shall I incur any liability for any damages, including, but limited to, direct, indirect, special, or consequential damages arising out of, resulting from, or any way connected to the use of the code provided, whether or not based upon warranty, contract, tort, or otherwise; whether or not injury was sustained by persons or property or otherwise; and whether or not loss was sustained from, or arose out of, the results of, the use if this code. ;p

Upvotes: 1

Related Questions