Exercise: PHP, simple calculator

In this exercise you will make a simple calculator using PHP.

Getting started

Make a PHP web page with a form element.

The methods must be post, not get.

First version, + only

Now make another PHP web page: This page is where you do the calculation an present the result.


Normally you use <form method="post" ...>.

Try to use method="get".

What difference does it make?
Use $_REQUEST or $_GET. What is the difference?

General question: How are data transported with HTTP GET and HTTP POST?

Next version, more arithmetic operators

The first version of the calculator only does '+'.

Now I want more!

Add a drop down list to the form (HTML select) with +, -, *, and /, and maybe even more operators.

Adapt the server side to handle different kinds of calculations:

  1. First version: Use PHP if ... else ... elseif statements.
  2. Second version: Use a PHP switch statement.

Refactoring: PHP and HTML should not be mixed

Refactor your PHP code so that PHP and HTML is not mixed (to much).

Put all the PHP code (except echo ...) in the to of the file.
Leave echo at the proper place of output inside the HTML

Extra: Post back

Many web programming concepts like JavaServer Faces and ASP.NET are modelled with Post back in mind: That is form elements does not refer to another page, rather to the same page.

Read about Post back in Lesson 9 : Post back in PHP.

Make a copy of your project and refactor the copy to use post back.

Extra: Refactoring: function

Make a user defined function to do the calculation.

  1. Simply wrap the PHP code in a function named calculate
    Make the function return the result.
    Use the result in echo.
  2. Make a copy of the function, name it calculate2
    Add parameters to the function: firstNumer, secondNumber, operationToBePerformed

Extra: Refactoring: class calculator

Make a PHP class calculator.

Inspiration (the first part only. The later part i quite advanced ...)

Extra: Refactoring: Separate file

Put the class calculator in a separate file.
Include the calculator file in the main file using the PHP syntax include or require.

Extra: CSS styling

Style your calculator to make it look nicer ...

Extra extra: Bootstrap

Style your calculator using the Bootstrap framework.