Home  >  Article  >  Backend Development  >  Write a calculator in PHP (complete code attached)

Write a calculator in PHP (complete code attached)

angryTom
angryTomforward
2020-01-31 17:48:4711162browse

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>

(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!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete