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

How Can I Build a PHP Calculator Using the Shunting Yard Algorithm?

Linda Hamilton
Linda HamiltonOriginal
2024-12-06 08:48:11653browse

How Can I Build a PHP Calculator Using the Shunting Yard Algorithm?

How to Create a Calculator Using PHP

Problem:

You want to develop a PHP calculator that evaluates simple algebraic expressions inputted by users in standard notation, displaying the evaluation process. The challenge lies in efficiently calculating the expression's value.

Answer:

Consider utilizing the Shunting Yard Algorithm for its simplicity and efficiency in evaluating algebraic expressions.

Shunting Yard Algorithm Implementation

Expression Definitions:

Create classes to represent different elements of the expression, such as parentheses, numbers, operators, and so on:

class Parenthesis extends TerminalExpression { ... }
class Number extends TerminalExpression { ... }
class Addition extends Operator { ... }
class Subtraction extends Operator { ... }
class Multiplication extends Operator { ... }
class Division extends Operator { ... }
class Power extends Operator { ... }

Stack Implementation:

class Stack {

    protected $data = array();

    // ... Methods for pushing, popping, and peeking from the stack ...
        
}

Executor Class:

The executor class parses the expression using the Shunting Yard algorithm and evaluates it:

class Math {

    // ... Fields and methods for parsing, running, and evaluating the expression ...
        
}

Example:

Here's an example of how to use the calculator:

$math = new Math();

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

$answer = $math->evaluate('1 + 2 * ((3 + 4) * 5 + 6)');
var_dump($answer);
// int(83)

This example covers grouping and operator precedence. However, you can customize the implementation to suit your specific requirements.

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

Statement:
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