Processing a formula comprised of array keys in PHP -


i write function process formulas comprised of array keys. example, (1+3+5+7-8)*9 or (1-3+5)/6 , etc suggestions?

edit: think it's better think of excel grid, field coordinates being array keys , 1 of fields being formula field (e.g. a1+a2-b2*b3)

   function convert_formula($formula, $formula_array) {     $callback = function($matches) use ($formula_array) {return $formula_array[(int) $matches[0]];};     $converted = preg_replace_callback("/[0-9]+/", $callback, $formula);     return eval("return $converted;");     }  $test_formula = '(3-1) * (3-10)'; $test_formula_array = array(323,67,82,56, 10 => 3);  echo convert_formula($test_formula, $test_formula_array);    

requires php 5.3.+ anon functions. you'll want first validate $formula argument ensure accepts numbers , math symbols before eval within function.

edit: going assumption tool instruct students on math , have pre-built set of formulas reference... eval 1 of dangerous functions of php, perhaps might consider running client side using javascript. when build page, dynamically create base reference javascript array containing possible values used in formula. way, using javascript's eval function, client builds , resolves formula on end. final evaluation passed server validates evaluation , gives final "correct/wrong" response. thought...


Comments

Popular posts from this blog

asp.net - repeatedly call AddImageUrl(url) to assemble pdf document -

java - Android recognize cell phone with keyboard or not? -

iphone - How would you achieve a LED Scrolling effect? -