Only PHP Code Calculator with Clickable Buttons as Input

后端 未结 1 465
故里飘歌
故里飘歌 2021-01-16 11:17

I am trying to code a calculator with only PHP and HTML code.

The Calculator should look like a real one and the buttons should be clickable.

Right now, I am

1条回答
  •  逝去的感伤
    2021-01-16 11:39

    This is my truly basic, almost style-less, pure-PHP calculator form:

    
    
    
    
    Basic PHP Calculator
    
    
    ";
    $buttons=[1,2,3,'+',4,5,6,'-',7,8,9,'*','C',0,'.','/','='];
    $pressed='';
    if(isset($_POST['pressed']) && in_array($_POST['pressed'],$buttons)){
        $pressed=$_POST['pressed'];
    }
    $stored='';
    if(isset($_POST['stored']) && preg_match('~^(?:[\d.]+[*/+-]?)+$~',$_POST['stored'],$out)){
        $stored=$out[0];    
    }
    $display=$stored.$pressed;
    //echo "$pressed & $stored & $display
    "; if($pressed=='C'){ $display=''; }elseif($pressed=='=' && preg_match('~^\d*\.?\d+(?:[*/+-]\d*\.?\d+)*$~',$stored)){ $display.=eval("return $stored;"); } echo "
    "; echo ""; echo ""; echo ""; echo ""; foreach(array_chunk($buttons,4) as $chunk){ echo ""; foreach($chunk as $button){ echo ""; } echo ""; } echo "
    $display
    "; echo ""; echo "
    "; ?>

    Here is a screenshot while I was testing:

    You can see that I've made every button a submit button with the same name, but different values. I use a single hidden input to preserve built expression. There will be many enhancements and considerations beyond this demo, it is up to you how far to go down this rabbit hole.


    P.S. For anyone who just unholstered their sidearm, squinted one eye, and sternly uttered "Hey, we don't take kindly to folks like you callin' eval() in these here parts!". Well, I've endeavored to adequately validate the string to be evaluated. If there is a known hole, please let me know and I'll try to fix it. Alternatively, this is my attempt to re-invent the eval() process with BOMDAS in mind:

    Code: (Demo)

    $stored="2+3*4/6";
    $components=preg_split('~([*/+-])~',$stored,NULL,PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
    while(($index=array_search('*',$components))!==false){
        array_splice($components,$index-1,3,$components[$index-1]*$components[$index+1]);
    }
    while(($index=array_search('/',$components))!==false){
        array_splice($components,$index-1,3,$components[$index-1]/$components[$index+1]);
    }
    while(($index=array_search('+',$components))!==false){
        array_splice($components,$index-1,3,$components[$index-1]+$components[$index+1]);
    }
    while(($index=array_search('-',$components))!==false){
        array_splice($components,$index-1,3,$components[$index-1]-$components[$index+1]);
    }
    echo current($components);  // 4
    

    0 讨论(0)
提交回复
热议问题