PHP code example of php-rpn / rpn

1. Go to this page and download the library: Download php-rpn/rpn library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

php-rpn / rpn example snippets


use Rpn\Expression;
use Rpn\Parsers\ShuntingYardParserBuilder;

// 1. Get a pre-configured parser for standard math operations.
$parser = ShuntingYardParserBuilder::math()->build();

// 2. Parse an infix expression into an RPN stream.
$rpnStream = $parser->parse('3 + 4 * 2');

// 3. Evaluate the stream.
$evaluator = new Expression();
echo $evaluator->evaluate($rpnStream)->value(); // Output: 11

use Rpn\Expression;
use Rpn\Parsers\ShuntingYardParserBuilder;

$parser = ShuntingYardParserBuilder::math()->build();
$evaluator = new Expression();

// Parse expressions with functions
$rpnStream = $parser->parse('sqrt(16) + pow(2, 3)');
echo $evaluator->evaluate($rpnStream)->value(); // Output: 12 (4 + 8)

use Rpn\Expression;
use Rpn\Parsers\ShuntingYardParserBuilder;

$parser = ShuntingYardParserBuilder::math()->build();
$evaluator = new Expression();

// Variables should start with a colon (:)

// Parse an expression with variables
$rpnStream = $parser->parse('(:a * :b + :c) * 2');

$evaluator->evaluate($rpnStream, [':a' => 3, ':b' => 4, ':c' => 5])->value(); // Output: 34

use Rpn\Expression;
use Rpn\Parsers\ShuntingYardParserBuilder;
use Rpn\Operators\OperatorInterface;
use Rpn\Operands\OperandInterface;
use Rpn\Enum\Associativity;
use Rpn\Enum\OperatorType;

// Define a custom "double factorial" operator
class DoubleFactorial implements OperatorInterface {
    public function getPrecedence(): int { return 10; }
    public function getAssociativity(): Associativity { return Associativity::Left; }
    public function getType(): OperatorType { return OperatorType::UnaryPostfix; }
    public function apply(OperandInterface ...$operands): OperandInterface {
        $val = $operands[0]->value();
        $result = 1;
        for ($i = $val; $i >= 1; $i -= 2) {
            $result *= $i;
        }
        return new \Rpn\Operands\Number($result);
    }
}

// Create a parser and add the new operator
$parser = ShuntingYardParserBuilder::math()
    ->addOperator('!!', new DoubleFactorial())
    ->build();

$evaluator = new Expression();

$rpnStream = $parser->parse('5!!'); // 5 * 3 * 1
echo $evaluator->evaluate($rpnStream)->value(); // Output: 15
bash
composer