How can tokens be normalized and executed step by step to accurately evaluate complex mathematical expressions in PHP?
To accurately evaluate complex mathematical expressions in PHP, tokens can be normalized by breaking down the expression into individual components such as numbers, operators, and parentheses. These tokens can then be executed step by step using a stack or a similar data structure to ensure the correct order of operations is followed. By parsing and evaluating the expression in this systematic manner, complex mathematical expressions can be accurately computed in PHP.
<?php
function evaluateExpression($expression) {
$tokens = preg_split('/([\+\-\*\/\(\) ])/', $expression, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
$stack = [];
foreach ($tokens as $token) {
if (is_numeric($token)) {
array_push($stack, $token);
} else {
$operand2 = array_pop($stack);
$operand1 = array_pop($stack);
switch ($token) {
case '+':
array_push($stack, $operand1 + $operand2);
break;
case '-':
array_push($stack, $operand1 - $operand2);
break;
case '*':
array_push($stack, $operand1 * $operand2);
break;
case '/':
array_push($stack, $operand1 / $operand2);
break;
}
}
}
return array_pop($stack);
}
$expression = "3 + 4 * (2 - 1)";
$result = evaluateExpression($expression);
echo "Result: " . $result; // Output: Result: 7
?>
Related Questions
- How can the separation of concerns principle (EVA - Input, Processing, Output) be applied to PHP scripts to improve code structure and maintainability?
- How can PHP be integrated with IIS to automatically authenticate users and retrieve their login names?
- What are the different methods to pass variables using Get in PHP?