I have save formulas and variables in a database and when I retrieve them I want php to calculate the value like so

$x = .0832;
$y = .0673;
$z = 1.5;

$formula = '$x -(($x-$y)*($z-1.0))';

        $newformula = str_replace('$x', $x, $formula);
	$newformula = str_replace('$y', $y, $newformula);
	$newformula = str_replace('$z', $z, $newformula);
	
	echo '</br>'.$newformula;

i can't figure out how to get the answer computed.

Thanks in advanced!!

I think you might be looking for the eval function.

Member Avatar

diafol

$x = .0832;
$y = .0673;
$z = 1.5;
 
$formula = $x -(($x-$y)*($z-1.0));
echo '</br>'.$formula;

Is that it?

I used this function that i found on the internet

function calculate_string( $mathString )    {
    $mathString = trim($mathString);     // trim white spaces
    $mathString = preg_replace ('[^0-9\+-\*\/\(\) ]', '', $mathString);    // remove any non-numbers chars; exception for math operators
 
    $compute = create_function("", "return (" . $mathString . ");" );
    return 0 + $compute();
	}
Member Avatar

diafol

And?

I'm not entirely sure what you want to do. Are you placing values into a ready made formula or do you want to create a formula on the fly and place vars into it to solve it?

eval() can be a security issue if user inputs are not filtered properly.
what is the issue with this pseudo function? Isn't it working as expected?

You can try curly braces also,
echo '</br>',{$newformula};

Hi,

Just my humble opinion..If you want your formula to do the calculation, then don't treat them as a text string.. For example $x = 1; echo $x, will give us 1 which is treated as integer rather a text string, and so forth.

Try this

<?php
	$x = .0832;
$y = .0673;
$z = 1.5;

$formula = $x -(($x-$y)*($z-1.0));

        $newformula = str_replace($x, $x, $formula);
	$newformula = str_replace($y, $y, $newformula);
	$newformula = str_replace($z, $z, $newformula);
	
	echo '</br>'.$newformula;
?>

The above codes should give you a result of 0.07525 if that's the answer you want to be calculated. Or do you want the derivatives of the $newformula? e.g. x² + 2x − 8 ->2x + 2 = 0 or => (x + 4)(x − 2).

Let me just add, that in case the $x, $y, and $z are given the way they are laid out on your codes above, then this will calculate the same result. The only time you will have to probably assign a new value for $x, $y, and $z in
$newformula = str_replace($x, $x, $formula);
$newformula1 = str_replace($y, $y, $newformula);
$newformula2 = str_replace($z, $z, $newformula);

if the values for $x, $y, and $z are not assigned, or there will be new value or values that the script needs to be included. Otherwise the codes below will suffice.

<?php
	$x = .0832;
$y = .0673;
$z = 1.5;

$formula = $x -(($x-$y)*($z-1.0));
echo '</br>'.$formula;
?>
Member Avatar

diafol

Didn't I see that somewhere before? :)