Reputation: 21
I am stuck on something in PHP
$l = $par['Length'];
$w = $par['Width'];
$d = $par['Depth'];
$length = $par['Expr_1'];
$width = $par['Expr_2'];
$par
is an array read from a database.
Length, Width, Depth are numbers
Expr_1 & Expr_2 are formulas stored as strings
ie something like this:
($l + .0625) * ($w + .125) * ($l + .125) * ($w + .0625) + 1.625
What should happen is that $l
$w
should substitute with the values. If I echo $l,$w,$d
independently they have the right values. If I echo $length or $width
it shows the formula.
Even when I try eval("$width = {$par['Expr_2']};");
it doesn't force it to calculate instead of just read the formula. I know the formula is right because if I manually stick it into $length
or $width
it works fine.
Upvotes: 2
Views: 1301
Reputation: 11
Assuming that you will not be passing "any user provided data into it without properly validating it beforehand."
The following seems to work well.
$width = $par['Expr_2'];
eval('$width = '.$width .';');
Upvotes: 0
Reputation: 21
Although amber's solution would have worked, I wanted to keep it simple and make all the work I did entering the formulas into the db not a waste. I simply combined $length / $width at the beginning of the string and : at the end and eval'd it.
Thanks, everyone
EDIT to add code that I used:
$l = $par['Length'];
$w = $par['Width'];
$d = $par['Depth'];
$par['Expr_1'] = '$length='.$par['Expr_1'].';';
eval($par['Expr_1']);
$par['Expr_2'] = '$width='.$par['Expr_2'].';';
eval($par['Expr_2']);
Upvotes: 0
Reputation: 527468
Variable interpolation into strings only happens when those strings are evaluated source code. When they're just values stored in variables, assignments don't do interpolation.
Better would be to store a simple parseable format that doesn't require full-blown eval()
. Here's some code that can store a format that looks like this:
L,0.5;W,0.2;D,0.3:4.7
which would be equivalent to (L+0.5)*(W+0.2)*(D+0.3)+4.7
:
$eqn_parts = explode(':', $input);
$add_part = $eqn_parts[1];
$mult_parts = explode(';', $eqn_parts[0]);
$accum = 1;
foreach($mult_parts as $part) {
$bits = explode(',', $part);
switch($bits[0]) {
case "L":
$accum *= ($length + (int)$bits[1]); break;
case "W":
$accum *= ($width + (int)$bits[1]); break;
case "D":
$accum *= ($depth + (int)$bits[1]); break;
}
}
$accum += (int)$add_part;
Upvotes: 1
Reputation: 7603
Instead of using eval
for the formulas... there is the possible option of using something like preg_replace()
instead... to just replace those formula variables coming from the database... and then converting/typecasting the replaced result to an (int)
or whatever data type you need this to be. Then computing the formula from there. Though... it might not be as reliable as eval
.
http://php.net/manual/en/function.preg-replace.php
Upvotes: 1