SHARE
TWEET

Untitled

a guest Sep 25th, 2018 80 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <?php
  2. mb_internal_encoding('utf-8');
  3. $input='243+6743-78*2=';
  4. $inputLength=strlen($input);
  5. $number=0;
  6. $result=0;
  7. $op='+';
  8.  
  9. function doMath($op,$result,$number) {
  10.    
  11.     return $op==='+'?$result+$number:($op==='-'?$result-$number:$result*$number);
  12. }
  13.  
  14.  
  15. for ($i=0;$i<$inputLength;$i++) {
  16.    
  17.     $char=mb_substr($input,$i,1);
  18.    
  19.     //validation and coercion step
  20.    
  21.     if (is_numeric($char)) {
  22.         $char=intval($char);
  23.     }
  24.     elseif (!is_numeric($char)&&!in_array($char,['-','+','=','*'])) {
  25.             echo "Enter correct value!"; exit();
  26.         }
  27.  
  28.     //math
  29.    
  30.     if ($char=='+'||$char=='-'||$char=='*'||$char=='=') {
  31.        
  32.         $result=doMath($op,$result,$number);
  33.        
  34.         $number=0;
  35.         $op=$char;
  36.        
  37.     } else {
  38.        
  39.         $number=$number*10+$char;
  40.        
  41.     }
  42.    
  43.     //when equation sign reached
  44.    
  45.     if ($op=='=') {
  46.         echo "". $result;
  47.     }
  48. }
  49. ?>
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top