Write a calculator in PHP (complete code attached)

angryTom
Release: 2023-04-08 11:42:01
forward
11171 people have browsed it

This article introduces how to write a calculator using PHP HTML Javascript technology. I hope it will be helpful to students who are learning PHP development!

Write a calculator in PHP (complete code attached)

Write a calculator in PHP

<body>
    <?php
    if (!empty($_POST)) {
        $op=$_POST[&#39;point&#39;];
        $sum1 = $_POST[&#39;sum1&#39;];
        $sum2 = $_POST[&#39;sum2&#39;];
        $sum = 0;
        if ($sum1 != &#39;&#39; && is_numeric($sum1) && $sum2 != &#39;&#39; && is_numeric($sum2)) {
            switch ($op) {
                case &#39;+&#39;:
                    $sum = $sum1 + $sum2;
                    break;
                case &#39;-&#39;:
                    $sum = $sum1 - $sum2;
                    break;
                case &#39;*&#39;:
                    $sum = $sum1 * $sum2;
                    break;
                case &#39;/&#39;:
                    $sum = $sum1 / $sum2;
                    break;
            }
            echo <<<shi
            <script>
                window.onload = function() {
                    document.getElementsByName(&#39;sum3&#39;)[0].setAttribute(&#39;value&#39;, &#39;$sum&#39;)
                    document.getElementsByName(&#39;sum1&#39;)[0].setAttribute(&#39;value&#39;, &#39;$sum1&#39;)
                    document.getElementsByName(&#39;sum2&#39;)[0].setAttribute(&#39;value&#39;, &#39;$sum2&#39;)
                    document.getElementsByName(&#39;{$op}&#39;)[0].setAttribute(&#39;selected&#39;,&#39;selected&#39;)
                }
            </script>
shi;
        } else {
            echo &#39;输入内容必须是数字&#39;;
        }
    };
    ?>
    <form action="" method=&#39;post&#39;>
        <input type="text" name="sum1">
        <select name=&#39;point&#39;>
            <option name=&#39;+&#39;>+</option>
            <option name=&#39;-&#39;>-</option>
            <option name=&#39;*&#39;>*</option>
            <option name=&#39;/&#39;>/</option>
        </select>
        <input type="text" name=&#39;sum2&#39;>
        <input type="submit" name=&#39;button&#39; value=&#39;=&#39;>
        <input type="text" name=&#39;sum3&#39;>
    </form>
</body>
Copy after login

(Free learning video tutorial sharing: php video tutorial)

The above is the detailed content of Write a calculator in PHP (complete code attached). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:cnblogs.com
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template