Program to evaluate simple expressions | A utility function to check if a given character is operand ; utility function to find value of and operand ; This function evaluates simple expressions . It returns - 1 if the given expression is invalid . ; Base Case : Given expression is empty ; The first character must be an operand , find its value ; Traverse the remaining characters in pairs ; The next character must be an operator , and next to next an operand ; If next to next character is not an operand ; Update result according to the operator ; If not a valid operator ; Driver Code
< ? php function isOperand ( $ c ) { return ( $ c >= '0' && $ c <= '9' ) ; } function value ( $ c ) { return ( $ c - '0' ) ; } function evaluate ( $ exp ) { $ len = strlen ( $ exp ) ; if ( $ len == 0 ) return -1 ; $ res = ( int ) ( value ( $ exp [ 0 ] ) ) ; for ( $ i = 1 ; $ i < $ len ; $ i += 2 ) { $ opr = $ exp [ $ i ] ; $ opd = $ exp [ $ i + 1 ] ; if ( ! isOperand ( $ opd ) ) return -1 ; if ( $ opr == ' + ' ) $ res += value ( $ opd ) ; else if ( $ opr == ' - ' ) $ res -= ( int ) ( value ( $ opd ) ) ; else if ( $ opr == ' * ' ) $ res *= ( int ) ( value ( $ opd ) ) ; else if ( $ opr == ' / ' ) $ res /= ( int ) ( value ( $ opd ) ) ; else return -1 ; } return $ res ; } $ expr1 = "1 + 2*5 + 3" ; $ res = evaluate ( $ expr1 ) ; ( $ res == -1 ) ? print ( $ expr1 . " ▁ is ▁ Invalid STRNEWLINE " ) : print ( " Value ▁ of ▁ " . $ expr1 . " ▁ is ▁ " . $ res . " STRNEWLINE " ) ; $ expr2 = "1 + 2*3" ; $ res = evaluate ( $ expr2 ) ; ( $ res == -1 ) ? print ( $ expr2 . " ▁ is ▁ Invalid STRNEWLINE " ) : print ( " Value ▁ of ▁ " . $ expr2 . " ▁ is ▁ " . $ res . " STRNEWLINE " ) ; $ expr3 = "4-2 + 6*3" ; $ res = evaluate ( $ expr3 ) ; ( $ res == -1 ) ? print ( $ expr3 . " ▁ is ▁ Invalid STRNEWLINE " ) : print ( " Value ▁ of ▁ " . $ expr3 . " ▁ is ▁ " . $ res . " STRNEWLINE " ) ; $ expr4 = "1 + + 2" ; $ res = evaluate ( $ expr4 ) ; ( $ res == -1 ) ? print ( $ expr4 . " ▁ is ▁ Invalid STRNEWLINE " ) : print ( " Value ▁ of ▁ " . $ expr4 . " ▁ is ▁ " . $ res . " STRNEWLINE " ) ; ? >