I have 3 variables and a formula that trusted users need to be able to define via a CMS. This formula will change over time and the value of the variables come from a database.
How can I work out the answer to the calculation? I assume eval is relevant but can't quite get it to work
$width = 10;
$height = 10;
$depth = 10;
$volumetric = '(W*H*D)/6000';
$volumetric = str_replace('W', $width, $volumetric);
$volumetric = str_replace('H', $height, $volumetric);
$volumetric = str_replace('D', $depth, $volumetric);
eval($volumetric);
This gives me:
Parse error: parse error in /path/to/vol.php(13) : eval()'d code on line 1
You need to be extremely careful with eval as you're giving people access to run commands directly on the server. Make sure to read the documentation thoroughly and understand the risks.
That said, you need to assign the result to a variable. You can tidy up what you're doing too, you only need one str_replace. Try this:
$width = 10;
$height = 10;
$depth = 10;
$volumetric = '(W*H*D)/6000';
$volumetric = str_replace(['W', 'H', 'D'], [$width, $height, $depth], $volumetric);
eval("\$result = $volumetric;");
echo $result;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With