PHP code example of zippovich2 / expressions-parser

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

    

zippovich2 / expressions-parser example snippets


use Zippovich2\ExpressionsParser\Parser\ArithmeticalParser;

$parser = new ArithmeticalParser();

// 45
$parser->eval('2 + (3^3) + 8 * (3 - 1)'); 

// 3.0001220703125
$parser->eval('3 + 4 * 2 / (1 - 5) ^ 2 ^ 3'); 

// 58
$parser->eval('58+(max(1, 2, 3)/3)'); 

use Zippovich2\ExpressionsParser\Parser\LogicalParser;

$parser = new LogicalParser();

// true
$parser->eval('true || false'); 

// false
$parser->eval('true && false'); 

// true
$parser->eval('true xor false'); 

// false
$parser->eval('true xor true'); 

use Zippovich2\ExpressionsParser\Parser\LogicalParser;
use Zippovich2\ExpressionsParser\OperatorFactory;

$parser = new LogicalParser();
$parser->addOperator(OperatorFactory::rightAssociative('**', function($a, $b){
    return $a ** $b;
}, 5));
$parser->addOperator(OperatorFactory::func('if', function($condition, $if, $else){
    return $condition ? $if : $else;
}));
$parser->addOperator(OperatorFactory::constant('e', M_E));

// false
$res = $parser->eval('if(2 < 1, true, false)');

// true
$res = $parser->eval('if(2 > 1, true, false)');

// 16
$res = $parser->eval('2**4');

// 3.718281828459
$res = $parser->eval('e+1');

use Zippovich2\ExpressionsParser\Parser;
use Zippovich2\ExpressionsParser\OperatorsList;
use Zippovich2\ExpressionsParser\OperatorFactory;

$operators = new OperatorsList();

$operators->add(OperatorFactory::leftAssociative('AND', function ($a, $b){
    return $a && $b;
}));

$parser = new Parser($operators);

// false
$parser->eval('1 AND 0');

// true
$parser->eval('1 AND 0');

use Zippovich2\ExpressionsParser\Parser;
use Zippovich2\ExpressionsParser\OperatorsList;
use Zippovich2\ExpressionsParser\OperatorFactory;

$operators = new OperatorsList();

$operators->add(OperatorFactory::leftAssociative('AND', function ($a, $b){
    return $a && $b;
}));

$operators->add(OperatorFactory::leftAssociative('OR'));

$defaultCallback = function ($operator, ...$parameters){
    switch ($operator){
        case 'OR':
            return $parameters[0] || $parameters[1];
    }
    
    throw new \LogicException('This code should not be reached.');
};

$parser = new Parser($operators);

// true
$parser->eval('1 AND 0 OR 1', $defaultCallback);

// false
$parser->eval('1 AND 0 OR 0', $defaultCallback);

/**
 * @throws \LogicException because no callback was provided for "OR" operator. 
 */
$parser->eval('1 AND 0 OR 0');