PHP code example of nxp / math-executor

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

    

nxp / math-executor example snippets


use NXP\MathExecutor;

$executor = new MathExecutor();

echo $executor->execute('1 + 2 * (2 - (4+10))^2 + sin(10)');

$executor->addFunction('concat', function($arg1, $arg2) {return $arg1 . $arg2;});

$executor->addFunction('round', function($num, int $precision = 0) {return round($num, $precision);});
$executor->calculate('round(17.119)'); // 17
$executor->calculate('round(17.119, 2)'); // 17.12

$executor->addFunction('average', function(...$args) {return array_sum($args) / count($args);});
$executor->calculate('average(1,3)'); // 2
$executor->calculate('average(1, 3, 4, 8)'); // 4

use NXP\Classes\Operator;

$executor->addOperator(new Operator(
    '%', // Operator sign
    false, // Is right associated operator
    180, // Operator priority
    function (&$stack)
    {
       $op2 = array_pop($stack);
       $op1 = array_pop($stack);
       $result = $op1->getValue() % $op2->getValue();

       return $result;
    }
));

$executor->setVar('var1', 0.15)->setVar('var2', 0.22);

echo $executor->execute("$var1 + var2");

$executor->setVar('monthly_salaries', [1800, 1900, 1200, 1600]);

echo $executor->execute("avg(monthly_salaries) * min([1.1, 1.3])");

$executor->setVarValidationHandler(function (string $name, $variable) {
    // allow all scalars, array and null
    if (is_scalar($variable) || is_array($variable) || $variable === null) {
        return;
    }
    // Allow variables of type DateTime, but not others
    if (! $variable instanceof \DateTime) {
        throw new MathExecutorException("Invalid variable type");
    }
});

$calculator = new MathExecutor();
$calculator->setVarNotFoundHandler(
    function ($varName) {
        if ($varName == 'trans') {
            return transmogrify();
        }
        return null;
    }
);

try {
    echo $executor->execute('1/0');
} catch (DivisionByZeroException $e) {
    echo $e->getMessage();
}

echo $executor->setDivisionByZeroIsZero()->execute('1/0');

$executor->addOperator("/", false, 180, function($a, $b) {
    if ($b == 0) {
        return null;
    }
    return $a / $b;
});
echo $executor->execute('1/0');

echo $executor->execute("1 + '2.5' * '.5' + myFunction('category')");

echo $executor->execute("countArticleSentences('My Best Article\'s Title')");

function if($condition, $returnIfTrue, $returnIfFalse)