Home > Backend Development > PHP Tutorial > How to Build a Calculator in PHP Using the Shunting Yard Algorithm?

How to Build a Calculator in PHP Using the Shunting Yard Algorithm?

Mary-Kate Olsen
Release: 2024-12-11 06:22:11
Original
118 people have browsed it

How to Build a Calculator in PHP Using the Shunting Yard Algorithm?

How to create a calculator in PHP?

In PHP, creating a calculator requires parsing and evaluating mathematical expressions entered by a user. This can be challenging, as it involves handling user input and applying mathematical operations.

Utilizing the Shunting Yard Algorithm

One recommended approach is to leverage the Shunting Yard Algorithm. This algorithm converts mathematical expressions into Reverse Polish Notation (RPN), which is easier to evaluate.

Example Implementation

Here's a simplified example using the Shunting Yard Algorithm:

// Terminal expression abstract class
abstract class TerminalExpression {

    public function operate() {
        return $this->value;
    }

    public function isOperator() {
        return false;
    }

    public function isParenthesis() {
        return false;
    }

    public function isNoOp() {
        return false;
    }
}

// Operator expression abstract class
abstract class Operator extends TerminalExpression {

    public function isOperator() {
        return true;
    }
}

// Stack implementation
class Stack {

    private $data = [];

    public function push($element) {
        $this->data[] = $element;
    }

    public function peek() {
        return end($this->data);
    }

    public function pop() {
        return array_pop($this->data);
    }
}

// Math class for evaluation
class Math {

    public function evaluate($expression) {
        $stack = $this->parse($expression);
        return $this->run($stack);
    }

    private function parse($expression) {
        $tokens = $this->tokenize($expression);
        $output = new Stack();
        $operators = new Stack();

        foreach ($tokens as $token) {
            $type = TerminalExpression::factory($token);

            if ($type->isOperator()) {
                $this->parseOperator($type, $output, $operators);
            } elseif ($type->isParenthesis()) {
                $this->parseParenthesis($type, $output, $operators);
            } else {
                $output->push($type);
            }
        }

        while (($op = $operators->pop())) {
            if ($op->isParenthesis()) {
                throw new RuntimeException('Mismatched Parenthesis');
            }
            $output->push($op);
        }

        return $output;
    }

    private function run(Stack $stack) {
        while (($operator = $stack->pop()) && $operator->isOperator()) {
            $value = $operator->operate($stack);
            if ($value !== null) {
                $stack->push(TerminalExpression::factory($value));
            }
        }
        return $operator ? $operator->render() : $this->render($stack);
    }

    protected function tokenize($string) {
        return preg_split('((\d+|\+|-|\(|\)|\*|/)|\s+)', $string, null, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
    }
}

$math = new Math();
$answer = $math->evaluate('(2 + 3) * 4');
var_dump($answer); // int(20)
Copy after login

This example demonstrates how to use the Shunting Yard Algorithm to parse and evaluate a simple mathematical expression.

The above is the detailed content of How to Build a Calculator in PHP Using the Shunting Yard Algorithm?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template