PHP code example of simon-forb / php-formula-interpreter

1. Go to this page and download the library: Download simon-forb/php-formula-interpreter 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/ */

    

simon-forb / php-formula-interpreter example snippets


$compiler = new FormulaInterpreter\Compiler();

$executable = $compiler->compile('2 + 2');

$result = $executable->run();
// $result equals 4

'2 * (3 + 2)'

'2 * (2 * (3 + 2 * (3 + 2)) + 2)'

'1 = 1' //true
'1 != 1' //false
'1 != 2' //true
'1 < 2' //true

'(4 > 0) AND (3 > 2)' //true
'(4 > 0) AND (3 < 2)' //false
'(4 > 0) OR (3 < 2)' //true
'(4 < 0) AND (3 < 2)' //false

'price * rate / 100'

$variables = [
   'user.name' => 'John Doe'
   'user.age' => '23'
];

$executable->run($variables);

'a = "Hello world"'

   'cos(0)'

   'pow(sqrt(4), 2)'

$compiler = new Compiler();
$compiler->registerFunction('foobar', function ($a, $b) {
    return $a + $b;
});
$executable = $compiler->compile("foobar(foo, bar)");
$params = [
    'foo' => 1,
    'bar' => 2
];
$executable->run($params);

$executable = $compiler->compile('foo + bar');

print_r($executable->getParameters());

    Array
    (
        [0] => foo
        [0] => bar
    )

composer 

$variables = [
   'price' => 40.2,
   'rate' => 12.8
];

$executable->run($variables);