codepad
[
create a new paste
]
login
|
about
Language:
C
C++
D
Haskell
Lua
OCaml
PHP
Perl
Plain Text
Python
Ruby
Scheme
Tcl
<?php //the different operators map to their respective function $opers = array ( '+' => function($val1, $val2){ return $val1+$val2; }, '-' => function($val1, $val2){ return $val1-$val2; }, '*' => function($val1, $val2){ return $val1*$val2; }, '/' => function($val1, $val2){ return $val1/$val2; }, ); function evalExpr($input) { //split the input on white space $expr = preg_split("/[ \t\n]+/", $input); //create the stack $stack = array(); foreach ($expr as $term) evaluate($stack, $term); //if this worked out correctly //we should only have the result on the stack if (sizeof($stack) == 1) return array_pop($stack); } function evaluate(&$stack, $term) { global $opers; //if this is a number if (is_numeric($term)) //push it on the stack array_push($stack, $term); //if this is an operator else if (array_key_exists($term, $opers)) { //pop top two values off the stack $val2 = array_pop($stack); $val1 = array_pop($stack); //get the function that goes with this operator $func = $opers[$term]; //get the result and push it back on the stack array_push($stack, $func($val1, $val2)); } } ?>
Private
[
?
]
Run code
Submit