Welcome, time to learn again.

I think that everyone heard, that you don’t need math in web dev. And that’s a little tricky Even though yes - stuff like linear algebra or some advanced calculus may not be the most valuable knowlegde for us, yet mathematical logic or arithmetic is very useful And that will be our focus today, I’ll also add something about sessions and present how useful they are

So, we will learn today

  1. Basic arithmetic operations (addition, division etc.)
  2. Square roots and exponentiation
  3. Logic operators
  4. Something about sessions
  5. switch statement

It will end with a short example project - a very basic calculator

With that said - let’s go

Numbers and fractions

Start with creating new variables, just like in previous article - let’s call them a and b(never call them like this in real life)

$a = 25;
$b = 5;

These, will be 2 values I’ll use later

This time, I used integers - but you can use whatever you want to Double and floats are also in PHP. It’s possible to write something like this

$c = -4.5;

And remember - decimal fractions are written with . (dot) and not ,(comma) With this said - let’s explore further

Basic arithmetic

Any basic mathematical operation is done, like on paper.

To do it, we use operators. Another term?

It’s a construct that takes an expression (one or more values) and then returns us something else, technically also becoming an expression

What does it mean - let’s see example

echo $a + $b;
// 30

+ here is an operator - it connects two values and then yields other value, also becoming the expression

Rest is similar

Subtraction - use -:

echo $a - $b;
// 20

Multiplying - use *:

echo $a * $b;
// 125

Division use /:

echo $a / $b;
// 5

And last operation - modulo (%)

echo $a % $b;

What is modulo? It’s remainder of division - if you divide 3 by 2 you get 1 and a 1 as a reminder.

No time to waste, let’s get further

Roots and exponentiation

Here, it gets a little bit trickier

To write the exponential expression - we have 2 methods

  1. using ** operator
    echo 5 ** 2;
    // 25
    
  2. Using pow() funtction
    echo pow(5, 2);
    // 25
    

Personally - first one suits me better. I like simplicity that comes with operators

And square roots. They don’t have any operator - just sqrt() function

echo sqrt($a);
// 5

But what if we want get other root than square one - We can use old trick - power to a fraction

echo pow(8, 1/3);
// 2

Remember that if you power something to a fraction with numerator = 1, you get a denominators root of that number

Let’s get to the last, and really important part

Logical Operations

Pay attention, as we will be using logical operators very often

First - some theoretical and more mathematical info

Let’s get the expression (with our previous variables)

$a + $b = 30
// 25 + 5 = 30

If we want to evaluate it’s logical value - we check if 25 + 5 really equals 30

And yes, it does - so our check will return true

var_dump((bool) ($a + $b == 30));
// bool(true) 

Quick side note: This (bool) inside var_dump indicates what type of data should get returned

And it does - now, what’s that strange symbol between $b and 30?

That’s a comparison operator named equal - this means “Do these 2 expressions have the same value?”. If yes, it returns true. If not - false;

Why not =? Because = is a symbol of assignment - It would create a lot of mess, so it was standardized to ==

Let’s see them all of those operators in action

  1. === - Identical. Difference between this and equal is, that it also checks type So this
    var_dump((bool) ($a + $b == 30.0));
    // bool(true)
    

Gives us true or 1 (it’s the same and can be used interchangeably)

But if we use ===

var_dump((bool) ($a + $b === 30.0));
// bool(false) 

We get false (or 0 - it’s the same too)

Why? We added 2 integers - so result is integer. Yet here, we are comparing it to a float And float 30.0 is not the same as int 30

  1. != - Not equal. The opposite of == - will return true if expressions don’t have the same value
var_dump((bool) ($a + $b != 32));
// bool(true)

Not equal has also it’s alternative - <>. But you shouldn’t use it in your code. != is much more readable.

I mentioned it, as it can sometimes be seen in older codes - so you know

  1. !== - Not identical. The difference here is the same as between == and ===. This operator checks also types

So this:

var_dump((bool) ($a + $b !== 30.0));
// bool(true)

Gives us true, because the types don’t match

  1. <, > - less than and greater than. I put them together because
    • We already know one of them - it appeared in pt. 3
    • They are identical to their math equivalent
var_dump((bool) ($a + $b > 10.0));
// bool(true) 

And the same goes another way - I hope you get the point of operators?

Now last ones:

  1. >= - Greater than or equal to. It will return true if expression on right side is grater or equal to one on the left side

It’s math equivalent is

var_dump((bool) ($a + $b >= 10)); // bool(true)
// And also
var_dump((bool) ($a + $b >= 30)); // bool(true)
  1. <= - Less than or equal to. This one is the opposite of previous one

It’s mathematical symbol is

var_dump((bool) ($a + $b <= 10)); // bool(false)
// And also
var_dump((bool) ($a + $b <= 30)); // bool(true)

And that’s it - pretty much every operator you need to know

For some further explanation - visiting PHP docs is recommended

So now, let’s leave the theory and start writing our calculator

Practical Project - Calculator

First start your server and create a new folder - I’ll call it calculator and inside index.php

What we need now is basic HTML template

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Calculator</title>
</head>
<body>
    <form action="calculate.php" method = "GET">
        <input type="number" name="num1" id="" />
        <input type="number" name="num2" id="" />
        <select name = "operation">
            <option value ="add">Add</option>
            <option value ="subtract">Subtract</option>
            <option value ="multiply">Multiply</option>
            <option value ="divide">Divide</option>
            <option value = "expon">Exponentiation</option>
            <option value = "root"> Square Root</option>
            <option value = "modulo">Modulo</option>
        </select>

        <button type="submit">Calculate</button>
    </form>
</body>
</html>

What is <select>? - It’s this drop-down form field

Select element in pratcise

It has operation as name - this works just as in any other form field.

And each <option> element represents… the option. So, content of the tag is the label in form field, but value is the value of $_GET['operation'] then in PHP

With this said - let’s dive deeper

Now, action element isn’t empty - so we will create a new file called calculate.php solely for PHP code.

Inside a file, add PHP tag and check if data is present, we will save it to additional variables and declare another one called result - it will be useful in the end

<?php

if(!isset($_GET['num1'])){
    header("Location: index.php");
    exit();
}

$num1 = $_GET['num1'];
$num2 = $_GET['num2'];
$operation = $_GET['operation'];
$result = 0;

Now, we could spend a lot of time writing if-else structures, creating really big mess (so-called spaghetti code).

But there is another, more optimal way

switch statement

Rhere is a structure, that can replace a lot of if-else code - so make it clearer

Let’s write and then analyze it

switch($operation){
    case "add": $result = $num1 + $num2; break;
    case "subtract": $result = $num1 - $num2; break;
    case "multiply": $result = $num1*$num2; break;
    case "divide": $result = $num1/$num2; break;
    case "expon": $result = $num1**$num2; break;
    case "root": $result = sqrt($num1); break;
    case "modulo": $result = $num1%$num2; break;

    default: $result = "Invalid operation chosen"; break;
}

So, step by step

Inside brackets switch takes a value which will then be compared - here it’s$operation

And then - we address the case

 case "add": $result = $num1 + $num2; break;

This can be represented as

if($operation == "add"){
   $result = $num1 + $num2;
}

And the same is done with each and every case - it compares if value in quotes is equal to $operation value

Also, we have 2 new keywords here

  1. break- It finishes the statement early If $num1 = 4 and $num2 = 2 and $operation = "divide", we would have everything below case "divide" executed So, first $result would really equal 2, then it would change to16, then again to 2, then 0 and in the end, we would get a message Invalid operation chosen Sometimes it may be useful - but don’t forget break; if you want to replace if-else with switch

  2. default - This case, matches if no other one was found before. If somehow $operations will be set to ILoveBananas, it doesn’t match at all So, code in default will be invoked - We’ll see Invalid operation chosen

(Yes, you have to think about such edge-cases. Not everyone will use your websites as they are meant to be used)

Now, let’s display the value

Append to the file

echo $result;

This file looks like this

<?php

if(!isset($_GET['num1'])){
    header("Location: index.php");
    exit();
}

$num1 = $_GET['num1'];
$num2 = $_GET['num2'];
$operation = $_GET['operation'];
$result = 0;

switch($operation){
    case "add": $result = $num1 + $num2; break;
    case "subtract": $result = $num1 - $num2; break;
    case "multiply": $result = $num1*$num2; break;
    case "divide": $result = $num1/$num2; break;
    case "expon": $result = $num1**$num2; break;
    case "root": $result = sqrt($num1); break;
    case "modulo": $result = $num1%$num2; break;

    default: $result = "Invalid operation chosen"; break;
}

echo $result;

After submitting the form - you should see a page with a number

That’s great, but wouldn’t we like to have it on the same page as form?

Let’s talk about session now

Sessions

First, at the beginning of each file add

session_start();

In index.php place it right above Doctype inside PHP tags

That function either starts, or resumes existing session.

So, if we start the session in index.php, then switch to calculate.php - it will get resumed

Then, we can use really important feature called Session Variables

To access them, you select a specific field in superglobal associative array called $_SESSION - You use it just like $_GET, but here you can add whatever you want without limitation

So, let’s create one for $result and redirect user to calculate page

$_SESSION['result'] = $result;

header("Location: index.php");

When it’s done, we can go to index.php and below form add a new PHP tag

<?php

?>

Don’t forget the closing here

Now, just display it like normal variable

echo $_SESSION['result'];

Right?

Not really - If you do that, and refresh the page without sending a form, you will see this messages

Warning: Undefined variable $_SESSION in [PATH REDACTED] on line 25

Warning: Trying to access array offset on value of type null in [PATH REDACTED] on line 25

Not so cool, how do we fix it? Go to the start of calculate.php. Do you remember this?

if(!isset($_GET['num1'])){
    // Code responsible for redirection
}

That’s what we have to do here too - check if the value is set, and if yes, display it

Simple, isn’t it? Now, let’s write it

        if(isset($_SESSION['result'])){
            echo "Result is:";
            echo $_SESSION['result'];
            exit();
        }

And it works! - no errors. Now let’s calculate something - like 5+2

Result

It also works - well done.

That’s how you have written you calculator - good job!

Conclusion

Another day, another thing learned - This was one of longer articles

Of course - code is available on GitHub for you. By the way, I realized that there is no code for part 3. It will be uploaded as well

I hope you liked it, and learned something

I am always open for your feedback - that’s what comments are for.

Check out other parts of this series and see you next time

Also, merry Christmas for you all