PHP code example of nadybot / math-parser

1. Go to this page and download the library: Download nadybot/math-parser 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/ */

    

nadybot / math-parser example snippets


use MathParser\StdMathParser;
use MathParser\Interpreting\Evaluator;

$parser = new StdMathParser();

// Generate an abstract syntax tree
$AST = $parser->parse('1+2');

// Do something with the AST, e.g. evaluate the expression:
$evaluator = new Evaluator();

$value = $AST->accept($evaluator);
echo $value;

$AST = $parser->parse('x+sqrt(y)');

$evaluator->setVariables([ 'x' => 2, 'y' => 3 ]);
$value = $AST->accept($evaluator);

use MathParser\Interpreting\Differentiator;

$differentiator = new Differentiator('x');
$f = $parser->parse('exp(2*x)-x*y');
$df = $f->accept($differentiator);

// $df now contains the AST of '2*exp(x)-y' and can be evaluated further
$evaluator->setVariables([ 'x' => 1, 'y' => 2 ]);
$df->accept($evaluator);