PHP code example of phramework / expression-parser

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

    

phramework / expression-parser example snippets



/*
 * Define a language
 * with a Boolean function "or"
 */
$language = (new Language())
    /*
     * Define 'or' function
     */
    ->set(
        'or',
        function(bool $l, bool $r) : bool {
            return $l || $r;
        }
    );

/*
 * Create an expression parser based on the language
 */
$parser = new ExpressionParser(
    $language
);

/*
 * Evaluate an expression, expect result to be true
 */
$result = $parser->evaluate([
    'or', // first argument is always the function name 
    true, // will be passed as or function's first argument
    false // will be passed as or function's second argument
]);


/*
 * Define a language
 * with "+" (addition) and "-" (subtraction) functions for float numbers
 */
$language = (new Language())
    /*
     * Define "+" (addition) function
     */
    ->set(
        '+',
        function(float $l, float $r) : float {
            return $l + $r;
        }
    )
    /*
     * Define "-" (subtraction) function
     */
    ->set(
        '-',
        function(float $l, float $r) : float {
            return $l - $r;
        }
    );

/*
 * Create an expression parser based on the language
 */
$parser = new ExpressionParser(
    $language
);

/*
 * Evaluate expression
 * expect result to be 5 + (4.5 - 1) = 8.5
 */
$result = $parser->evaluate([
    '+',
    5,
    [
        '-',
        4.5,
        1
    ],
]);