Created
June 6, 2020 06:34
-
-
Save AdamZWinter/c0aeba1820f7467451dc424665732a59 to your computer and use it in GitHub Desktop.
Evaluating math expressions written as strings
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
echo '<p>'; | |
function evaluate_everything($values, $expressions) { | |
$output = []; | |
foreach($expressions as $expression) { | |
$row = []; | |
foreach($values as $value){ | |
$str = ''; | |
eval("\$str = \"$expression\";"); | |
$result= eval('return '.$str.';'); | |
array_push($row, $result); | |
} | |
array_push($output, $row); | |
} | |
return $output; | |
} | |
$values = [1, 2, 3]; | |
$expression1 = '5*$value + 18'; | |
$expression2 = '10*$value - 4'; | |
$expression3 = '$value + 42'; | |
$expressions = [$expression1, $expression2, $expression3]; | |
$resultArray = evaluate_everything($values, $expressions); | |
var_dump($resultArray); | |
echo '<br><br>'; | |
$value = 5; | |
eval("\$value = \"$expression3\";"); | |
$result= eval('return '.$value.';'); | |
echo $result; | |
echo '<br><br>'; | |
$string = 'cup'; | |
$name = 'coffee'; | |
$str = 'This is a $string with my $name in it.'; | |
echo $str. "\n"; | |
eval("\$str = \"$str\";"); | |
echo $str. "\n"; | |
echo '<p>'; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment