d_mc_a Posted May 8, 2007 Share Posted May 8, 2007 Sorry if this has already been answered before but it is a hard problem to find an answer for. I am making a simple web-based interface that will allow users to add shapes into a DB. This will involve uploading a shape description, a jpeg of the shape and an equation for the area of the shape. It doesn't have to be too dynamic so i've kept the equation as a standard format, using x0 -> xn as the variables for the equation. For example, the equation for the area of a square would be x0 * x0 ( length * length ) as there is only one variable for deriving the area of a square. A rectangle would be x0 * x1 ( length * height ) etc. I then have code that reads the equation and counts how many variables, assigns names to these variables etc. This part is all fine. When the user selects a rectangle and enters 2 as variable1 and 3 as variable2, the code will retrieve x0*x1 as the rectangle's equation, replace the x0 with 2 and x1 with 3, using str_replace() function. This all works fine. So, I'm left with a string stored under a variable with value 2*3 The only problem is that i don't know how to calculate that string. I don't know how i would return a value of 6. Will it not always return the value as "2*3" because it is a string?!? God, i hope this isn't a stupidly simple solution Any help would be appreciated Link to comment https://forums.phpfreaks.com/topic/50493-calculating-an-equation-stored-in-a-string/ Share on other sites More sharing options...
utexas_pjm Posted May 8, 2007 Share Posted May 8, 2007 Use the eval function. <?php eval('$sum = 1 + 1;'); echo $sum; // prints 2 ?> Best, Patrick Link to comment https://forums.phpfreaks.com/topic/50493-calculating-an-equation-stored-in-a-string/#findComment-248087 Share on other sites More sharing options...
d_mc_a Posted May 8, 2007 Author Share Posted May 8, 2007 Excellent, Thanks alot. In case anyone else is interested, I used: eval('$result = '.$Equation.';'); echo $result; Where $Equation = "2*2"; Thanks again Link to comment https://forums.phpfreaks.com/topic/50493-calculating-an-equation-stored-in-a-string/#findComment-248094 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.