Simple Four Operations Calculator Function Example Implemented by PHP

  • 2021-08-21 19:51:22
  • OfStack

In this paper, the simple four-operation calculator function realized by PHP is described with examples. Share it for your reference, as follows:

php implements a simple 4-arithmetic calculator (the priority of parentheses is not supported yet). It's great to use stack as a data structure to evaluate expressions.

The stack structure can be used here, because the array of php has the characteristics of stack "naturally", so the array is directly used here. Of course, you can use the stack structure to write, the reason is 1.

My predecessor (a Polish scientist) is calculating four expressions with brackets, using inverse Polish algorithm (suffix expression). It's amazing! ! In fact, the code code is not difficult. What is difficult is the guidance of the algorithm. It is necessary to understand the algorithm before coding.


<?php
$num_arr = array();//  Declare number stack 
$op_arr = array();//  Declare symbol stack 
$str = "10+6*2-18/2-2";
preg_match_all('/./', $str, $arr);//  Decompose the operation string into each character to $arr Array 
$str_arr = $arr[0];
$length = count($str_arr);
$pre_num = '';
//  Start stacking 
for($i=0; $i<$length; $i++){
  $val = $str_arr[$i];
  //  Figures 
  if (is_numeric($val)){
    $pre_num .= $val;//  Under consideration 1 The case where 10 characters may also be numbers (multiple digits) 
    if($i+1>=$length || isOper($str_arr[$i+1])){//  Under 1 If the number is an operator or the end is over, the number is stuffed into the number stack 
      array_push($num_arr, $pre_num);
      $pre_num = '';
    }
  //  The symbol judges the priority and chooses whether to enter the stack or not 
  } else if (isOper($val)){
    if (count($op_arr)>0){
      //  To judge the priority, as long as it is not greater than the priority at the top of the symbol stack, it will start to calculate. Until the priority is greater than the top of the stack, it will not put this operator into the stack after calculation 
      while (end($op_arr) && priority($val) <= priority(end($op_arr))){
        calc($num_arr, $op_arr);
      }
    }
    array_push($op_arr, $val);
  }
}
//echo '<pre>';
//print_r($num_arr);
//print_r($op_arr);
//  Calculate the remaining in the stack 
while(count($num_arr)>0){
  calc($num_arr, $op_arr);
  if (count($num_arr)==1){
    $result = array_pop($num_arr);
    break;
  }
}
echo $str,' = ', $result;
//  Calculate, get two numbers of the number stack, and symbolize the operator at the top of the stack 
function calc(&$num_arr, &$op_arr){
  if (count($num_arr)>0){
    $num1 = array_pop($num_arr);
    $num2 = array_pop($num_arr);
    $op = array_pop($op_arr);
    if ($op=='*') $re = $num1*$num2;
    if ($op=='/') $re = $num2/$num1;//  Pay attention to the order here. The stack is first in and then out, so $num2 Is a dividend 
    if ($op=='+') $re = $num2+$num1;
    if ($op=='-') $re = $num2-$num1;
    array_push($num_arr, $re);
  }
}
//  Get priority 
function priority($str){
  if ($str == '*' || $str == '/'){
    return 1;
  } else {
    return 0;
  }
}
//  Determine whether it is an operator 
function isOper($oper){
  $oper_array = array('+','-','*','/');
  if (in_array($oper, $oper_array)){
    return true;
  }
  return false;
}

Run results:


10+6*2-18/2-2 = 11

PS: Here are some computing tools recommended for your reference in the next step:

On-line 1 yuan function (equation) solution calculation tool;
http://tools.ofstack.com/jisuanqi/equ_jisuanqi

Scientific calculator online _ advanced calculator online calculation:
http://tools.ofstack.com/jisuanqi/jsqkexue

Online Calculator _ Standard Calculator:
http://tools.ofstack.com/jisuanqi/jsq

For more readers interested in PHP related contents, please check the special topics of this site: "Summary of PHP Mathematical Operation Skills", "Summary of PHP Operation and Operator Usage", "Summary of php String (string) Usage", "Encyclopedia of PHP Array (Array) Operation Skills", "Tutorial on PHP Data Structure and Algorithm", "Summary of php Programming Algorithm" and "Summary of php Regular Expression Usage"

I hope this article is helpful to everyone's PHP programming.


Related articles: