Skip to content

Instantly share code, notes, and snippets.

@AdamZWinter
Created June 6, 2020 06:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AdamZWinter/c0aeba1820f7467451dc424665732a59 to your computer and use it in GitHub Desktop.
Save AdamZWinter/c0aeba1820f7467451dc424665732a59 to your computer and use it in GitHub Desktop.
Evaluating math expressions written as strings
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