Evaluate an array expression with numbers , + and | Function to find the sum of given array ; if string is empty ; stoi function to convert string into integer ; cast to convert string into integer ; Find operator ; If operator is equal to ' + ' , add value in sum variable else subtract ; Driver code
< ? php function calculateSum ( $ arr , $ n ) { if ( $ n == 0 ) return 0 ; $ s = $ arr [ 0 ] ; $ value = ( int ) $ s ; $ sum = $ value ; for ( $ i = 2 ; $ i < $ n ; $ i = $ i + 2 ) { $ s = $ arr [ $ i ] ; $ value = ( int ) $ s ; $ operation = $ arr [ $ i - 1 ] ; if ( $ operation == ' + ' ) $ sum += $ value ; else if ( $ operation == ' - ' ) $ sum -= $ value ; } return $ sum ; } $ arr = array ( "3" , " + " , "4" , " - " , "7" , " + " , "13" ) ; $ n = sizeof ( $ arr ) / sizeof ( $ arr [ 0 ] ) ; echo calculateSum ( $ arr , $ n ) ; ? >