PHP code example of jzaaa / string-calc

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

    

jzaaa / string-calc example snippets


$stringCalc = new ChrisKonnertz\StringCalc\StringCalc();

$term = '1+2';

$result = $stringCalc->calculate($term); // $result will contain 3

$r          = [
    '$input' => 1000,
    '$cond1' => true,
    '$cond2' => false,
];
$math       = [
    '$bonus1'    => 'if($cond1, 30, 0)',
    '$bonus2'    => 'if($cond1 && !$cond2, 99, 0)',
    '$deduction' => '$input * 0.15',
    '$result'    => '$input - $deduction + $bonus1 + $bonus2',
];
$stringCalc = new ChrisKonnertz\StringCalc\StringCalc();
foreach ($math as $variable => $term) {
    $r[$variable] = $stringCalc->calculate($term, $r);
}
print_r($r);

try {
    $result = $stringCalc->calculate('min()');
} catch (Exceptions\StringCalcException $exception) {
    ... // Handle exception
} catch (\Exception $exception) {
    ... // Handle exception.
}

$term = '1+(2+max(-3,3))';

$tokens = $stringCalc->tokenize($term);

foreach ($tokens as $token) {
    echo ' '.$token.' ';
}

$term = '1+(2+max(-3,3))';

$tokens = $stringCalc->tokenize($term);

$rootNode = $stringCalc->parse($tokens);

$rootNode->traverse(function($node, $level)
{
    echo str_repeat('__', $level).' ['.get_class($node).']<br>';
});

class ExampleClassOne extends AbstractConstant
{
    protected $identifiers = ['exampleConst'];

    protected $value = 123;
}

// The AbstractSymbol class has this dependency:
$stringHelper = $container->get('stringcalc_stringhelper');
$symbol = new ExampleClassOne($stringHelper);
$replaceSymbol = ExampleClassTwo::class;

$stringCalc->addSymbol($symbol, $replaceSymbol);

if (sizeof($arguments) < 1) {
    throw new NumberOfArgumentsException('Error: Expected at least one argument, none given.');
}
`
+
-
*
/
<
<=
>
>=
==
= // same as '=='
!=
||
&&

3+1,2     // Usage out of scope / missusage as decimal mark
max(1,,3) // Missing calculable expression between separators