Build a Calculator with PHP

Build a Calculator with PHP

ยท

7 min read

Prerequisites: HTML and CSS knowledge is helpful but not mandatory

What is PHP?

PHP stands for Hypertext Preprocessor, you can say it has a recursive initialism ๐Ÿ˜ƒ It is a server-side programming language that makes it easy to build dynamic web applications.

If you already know how to build websites with HTML and CSS, that's pretty damn awesome! But let's say you need to make your website more dynamic, for example, create a login system, or a social network where users can post something. You'll need a database management system to store your website's user details and posts. In order to connect your website to the database, you will need a server-side programming language. There are many different options to pick from, but in this lesson, we will use PHP.

In this lesson, we will not be connecting to the database or performing user authentication. This will be a simple use of the PHP language to implement a calculator.

PHP does not run on the browser, but on the server, that's why it's called a 'server-side' programming language. In other to use PHP, we will need to set up a server to host our files. Once the server runs our PHP codes, it sends the output in form of HTML, we can then style it our desired styling so our website looks nice. Don't worry, I'll link the code to everything used in this lesson so you can check and compare with yours. Also, feel free to say hi to me on Twitter. Ready to build your calculator? let's go!

Setting up our local environment

To run PHP, you need a server. You can turn our computer into a server to run our PHP code. To accomplish this, you will install a web server solution stack on your computer. There are a number of available option, I'll list my suggestions below:

Windows / Linux: XAMPP

Mac: MAMP

Once you have the software installed, It should look like this:

Windows / Linux:

Screenshot 2021-06-22 at 19.26.44.png

Mac:

Screenshot 2021-06-22 at 19.27.10.png

Next, you'll need to navigate to the htdocs directory. You can find it on:

Windows: C:\xampp\htdocs

Linux: /opt/lampp/htdocs/ ~/Desktop/htdocs/

Mac: /Applications/MAMP/htdocs

This is where we will write our PHP code.

If you are able to make it this far congrats! Now let's write some code.

Writing the HTML

Let's write some simple HTML code that displays a basic form with two text inputs, one select field with five options, and one button on the page.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Calculator</title>
</head>
<body>
  <h1>Calculator World</h1>
  <form>
    <input type="text" placeholder="operand 1">
      <select>
          <option selected>None</option>
          <option>Add</option>
          <option>Subtract</option>
          <option>Multiply</option>
          <option>Divide</option>
      </select>
    <input type="text" placeholder="operand 2">
    <button>=</button>
  <div>
  </div>
  </form>
</body>
</html>

Your web page would look like this.

Screenshot 2021-06-22 at 21.42.27.png

You're doing awesome, next. we will style our page, so it looks clean to some extent. Feel free to skip this section if don't care about styling.

Styling with CSS

You can style your calculator however you want, I'll just give mine some basic styling. See code below.

*{
    box-sizing: border-box;
    padding: 0;
    margin: 0;
}
body {
    display: flex;
    height: 100vh;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    background: lightgray;
}
h1 {
    margin-top: -10%;
    margin-bottom: 26px;
    font-size: 3.8rem;
    font-family: monospace;
}
form {
    display: flex;
    width: 80%;
    justify-content: space-evenly;
    align-items: center;
    background: whitesmoke;
    border-radius: 30px;
}
form input, button, select {
    padding: 20px;
    font-size: 1.2rem;
    border: none;
    background: inherit;
}
form input:focus {
    outline: 1px solid dimgray;
}

form button {
    background: dimgray;
    color: whitesmoke;
    border-radius: 50%;
}
div {
    color: dimgray;
    font-weight: 900;
    font-size: 1.2rem;
    display: flex;
    justify-content: center;
    align-items: center;
}

@media screen and (max-width: 600px) {
    h1 {
        font-size: 3rem;
    }
    form {
        width: 95%;
        padding: 0 5%;
    }
    form input, button, select {
        width: 100%;
        margin: 0 5px;
        border-radius: 20px;
    }
    form button {
        /*border-radius: 0;*/
        /*padding-left: 20px;*/
        /*padding-right: 0;*/
        width: 10%;
    }
}

Next, let's connect our CSS to the HTML by including the link tag. See the example below:

    <link rel="stylesheet" href="./style.css">

Your calculator would look similar to this if you used my style. If you styled yours differently, I'd like to see it ๐Ÿ˜ƒ simply tag me on Twitter and I'll check it out.

Screenshot 2021-06-22 at 19.52.17.png

Now, Let's enable the calculator to perform some basic calculations.

Giving it Functionality

PHP makes it easy to mix and match code within our HTML code using these tags <?php ?>. Anything written within those tags is regarded as valid PHP code. Be sure to save your file with the .php file extension.

We want whatever value the user inputted to get displayed after the = button. So within our form, just after the button element, we will write some PHP code to calculate user inputs as requested.

To get user inputs, we will need to give each element inside the form a name as shown below:

    <input type="text" placeholder="operand 1" name="one">
    <select name="operator">
...
    <input type="text" placeholder="operand 2" name="two">
    <button name="equals">=</button>

Then, we'll give the form a method that specifies what request type we will use in sending the form. For this, we have two options, POST or GET. We will use the latter in our code. Then we need to set an action attribute that tells the browser which file will process the form it's sending, in this case, it's going to be the same file. My file is named index.php. If you named your file differently, be sure to check that it matches with the value provided in the action attribute. See the example below.

  <form action="index.php" method="GET">

Next, we will target each element inside the form and write some logic on them. I'll show the PHP code in its entirety below, then explain what each line means afterward.

<div>
      <?php
      if(isset($_GET['equals'])){
            $operandOne = $_GET['one'];
            $operandTwo = $_GET['two'];
            switch ($_GET['operator']){
                case 'None':
                    echo 'Select and operator';
                break;
                case 'Add':
                     echo $operandOne + $operandTwo;
                break;
                case 'Subtract':
                      echo $operandOne - $operandTwo;
                break;
                case 'Multiply':
                      echo $operandOne * $operandTwo;
                break;
                case 'Divide':
                     echo $operandOne / $operandTwo;
                break;
                default:
                    echo 'Nothing was supplied';
                break;
            }
        }else {
            echo '0';
        }
      ?>
  </div>

Explaining the above PHP code:

  1. <?php Starts the PHP tag so anything we write within it is regarded as valid PHP code.
  2. if(isset($_GET['equals'])){ Checks if the button, which has the name 'equals' has been clicked
  3. $operandOne = $_GET['one']; This statement declares a variable and initializes its value to whatever got passed in by the user into the first input field with the name 'one'.
  4. $operandTwo = $_GET['two']; Creates a variable and initializes its values to what got passed into the second input field with name 'two'.
  5. switch ($_GET['operator']){ A switch statement on what option got selected by the user on the select element.
  6. case 'None': This line says if the user selected None, perform the following action.
  7. echo 'Select and operator'; This string gets printed on the page
  8. break; Ends the switch statement
  9. case 'Add': If the user selects Add, perform the following action.
  10. echo $operandOne + $operandTwo; Add both values and print the sum on the page
  11. break; Ends the switch statement
  12. case 'Subtract': If the user selects Subtract, perform the following action.
  13. echo $operandOne - $operandTwo; Subtract the second value from the first and print the result on the page
  14. break; Ends the switch statement
  15. case 'Multiply': If the user selects Multiply, perform the following action.
  16. echo $operandOne * $operandTwo; Multiply both values and print the result on the page
  17. break; Ends the switch statement
  18. case 'Divide': If the user selects Divide, perform the following action.
  19. echo $operandOne / $operandTwo; Divide the second value from the first and print the result on the page
  20. break; Ends the switch statement
  21. default: If none of the above happens, do the following
  22. echo 'Nothing was supplied'; Prints the string
  23. break; End the program
  24. } Ends Switch block
  25. }else { Else statement
  26. echo '0'; Prints string to the screen until the if statement evaluates to true
  27. } Ends the Else statement
  28. ?> Closes the PHP tag

Seeing it work

Thanks for reading this far, I hope you found this article helpful. If you got stuck at any point, please see the complete code on Github