search
HomeBackend DevelopmentPHP TutorialPHP study notes - simple calculator script PHP from entry to proficiency PHP learning website php100

What is implemented in PHP this time is: the user inputs two numbers, and then selects one or more of the four operators of addition, subtraction, multiplication and division to display the calculation results.

My idea is this: create a form in HTML, including: 1. Selection box, allowing the user to select addition, subtraction, multiplication and division operations, and the selected results are stored in the operation array; 2. Text box, allowing the user to enter the required The calculated numbers and input results are stored in the num array; 3. Submit button to submit the form content. The form is submitted directly to this php page for processing using the POST method, where $_POST['operation'] stores operator information, and $_POST[num'] stores the data to participate in the operation. Determine the operator in the php script, perform the corresponding calculation, save the result to the array of $msg, and finally output $msg.

Okay, let’s go straight to the code:

<?php $result=array();  //用来保存计算结果的数组
$msg=array();     //保存结果消息的数组
$i=0;             //结果的个数
$error="";        //错误消息
if(isset($_POST[&#39;operation&#39;])){    //如果已经选择了运算符
    if((""!=$_POST[&#39;num&#39;][0])&&""!=($_POST[&#39;num&#39;][1])){   //输入文档框内容部位空
    $num1=(double)$_POST[&#39;num&#39;][0];                       //从字符串强制转换成double型的类型数据
    $num2=(double)$_POST[&#39;num&#39;][1];
    foreach($_POST[&#39;operation&#39;] as $op){                   //读取所选择的运算符
        switch($op){                                       //判断运算符属于哪一类
            case &#39;add&#39;:
               $result[$i]=$num1+$num2;                     //加法
               $msg[$i]="$num1"."+"."$num2"."="."$result[$i]";//将完整的算数式保存到消息数组里面     
               $i++;            
               break;
               
            case &#39;sub&#39;:
               $result[$i]=$num1-$num2;                      //减法
               $msg[$i]="$num1"."-"."$num2"."="."$result[$i]";//将完整的算数式保存到消息数组里面 
               $i++;            
               break;
               
            case &#39;mul&#39;:
               $result[$i]=$num1*$num2;                       //乘法
               $msg[$i]="$num1"."*"."$num2"."="."$result[$i]";//将完整的算数式保存到消息数组里面 
               $i++;            
               break;
               
            case &#39;div&#39;:
               if($_POST[&#39;num&#39;][1]!=0){                       //保证被除数不能为0
               $result[$i]=$num1/$num2;                        //除法
               $msg[$i]="$num1"."/"."$num2"."="."$result[$i]"; //将完整的算数式保存到消息数组里面 
               $i++;
               }
               else $error="被除数不能为0\n" ;                //如果除数为0,错误消息有提示       
               break;
             }
        }
    }
    else {                                                    //输入的数字有为空的情况
        if( ""!=$_POST[&#39;num&#39;][0] )              
            $error.="请输入num 1 \n";                         //记录到错误消息中
        if( ""!=$_POST[&#39;num&#39;][1] )
            $error.="请输入num 2 \n"; 
         
        }
}

?>




请选择运算符:



"; echo "计算结果如下:"."
"; foreach($msg as $str) echo $str."
"; echo $error; } ?>

The running interface is as follows:

PHP study notes - simple calculator script PHP from entry to proficiency PHP learning website php100

Input 13, 12

If all operators are selected:

PHP study notes - simple calculator script PHP from entry to proficiency PHP learning website php100

Ratings and improvements:

After testing, it was found that there are some defects. For example: every time after inputting data and submitting, the calculation results are displayed, but the page is also updated, and the originally entered data is gone. The improved result should be like this: after each submission, the text box will save the last record, but the check box will not be saved. The specific implementation is to set properties in the text box. I'm not particularly familiar with this, and I'm too lazy to do it now, so I'll just put it aside for now.

As for the code, there are many variables used in the PHP script, and the memory consumption is correspondingly large, so if variables such as $result[], $num1, and $num2 are not called by other scripts, they can be omitted; but in order Better scalability. When adding functions, you do not need to significantly change the original code. It is better to keep it.

Interested readers can go to http://www.beartracker.top/server1.php to test. Corrections are welcome ^_^

The above introduces the PHP learning notes - a simple calculator script, including PHP learning content. I hope it will be helpful to friends who are interested in PHP tutorials.

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

Simple Guide: Sending Email with PHP ScriptSimple Guide: Sending Email with PHP ScriptMay 12, 2025 am 12:02 AM

PHPisusedforsendingemailsduetoitsbuilt-inmail()functionandsupportivelibrarieslikePHPMailerandSwiftMailer.1)Usethemail()functionforbasicemails,butithaslimitations.2)EmployPHPMailerforadvancedfeatureslikeHTMLemailsandattachments.3)Improvedeliverability

PHP Performance: Identifying and Fixing BottlenecksPHP Performance: Identifying and Fixing BottlenecksMay 11, 2025 am 12:13 AM

PHP performance bottlenecks can be solved through the following steps: 1) Use Xdebug or Blackfire for performance analysis to find out the problem; 2) Optimize database queries and use caches, such as APCu; 3) Use efficient functions such as array_filter to optimize array operations; 4) Configure OPcache for bytecode cache; 5) Optimize the front-end, such as reducing HTTP requests and optimizing pictures; 6) Continuously monitor and optimize performance. Through these methods, the performance of PHP applications can be significantly improved.

Dependency Injection for PHP: a quick summaryDependency Injection for PHP: a quick summaryMay 11, 2025 am 12:09 AM

DependencyInjection(DI)inPHPisadesignpatternthatmanagesandreducesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itallowspassingdependencieslikedatabaseconnectionstoclassesasparameters,facilitatingeasiertestingandscalability.

Increase PHP Performance: Caching Strategies & TechniquesIncrease PHP Performance: Caching Strategies & TechniquesMay 11, 2025 am 12:08 AM

CachingimprovesPHPperformancebystoringresultsofcomputationsorqueriesforquickretrieval,reducingserverloadandenhancingresponsetimes.Effectivestrategiesinclude:1)Opcodecaching,whichstorescompiledPHPscriptsinmemorytoskipcompilation;2)DatacachingusingMemc

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools