PHP 0 to hero pt.5 - Math and Sessions in PHP
Tags: php, webdev, beginners, tutorial
Published: 2023-12-21 18:06:39

Welcome again - Now we start with a part 4 of this crash course

I think that everyone heard, that math is useless in **web dev** (yes, I bolded it purposefully) - I agree and disagree at the same time. 
Even though yes - stuff like linear algebra may not be the most valuable for us, yet mathematical logic or arithmetic is used very often here

And that will be our focus today - we will learn

1. Basic arithmetic operations (addition, division etc.)
2. Square roots and exponentiation
3. Logic operators
4. Sessions

It will end with a short example project - a very basic calculator
With some new, fancy stuff like sessions and `switch` statement 

With that said - let's go

## Setting up

Do you remember variables from the previous article? That's what we will use a lot today

So, start with creating new variables - let's call them `a` and `b`
```php
$a = 25;
$b = 5;
```

These will be 2 values I'll use - If anything changes, it will be mentioned

But it can be whatever you want - even negative or fractions, like
```php
$c = -4.5;
```

And remember - decimal fractions are written with `.` (dot) and not `,`(comma)
With this knowledge - let's go

## Basic arithmetic

This is very easy - any basic mathematical operation is done, like on paper. 

To do it, we use **operators**. Another strange term? Not really. It's just 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
```php
echo $a + $b;
// 30
```
`+` here is a **operator** - it connects to values and does something to them and, let's say, "merge" with them

And that's how you add 2 numbers in PHP - congrats

Rest is similar 

Subtraction:
```php
echo $a - $b;
// 20
```
Multiplying:
```php
echo $a * $b;
// 125
```
Division:
```php
echo $a / $b;
// 5
```
And last operation - **modulo**
```php
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.

And that's how, you have learned everything about basic math in PHP - 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
```php
echo 5 ** 2;
// 25
```
2. Using `pow()` funtction
```php
echo pow(5, 2);
// 25
```

For me - first one is better. I like simplicity that comes with operators

And (sadly) square roots don't have any operator - just `sqrt()` function 
```php
echo sqrt($a);
// 5
```

But what if we want get other root than square one - let's use old trick we have learned in high school
```php
echo pow(8, 1/3);
// 2
```

Remember that if you power something to inverse of a fraction, you get a denominators root of that number

Sounds easy now - let's get to the last, and really important part

## Logical Operations

To be fair - that's the most important part of this article, 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
```php
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 **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's standardized to `==`

That's another comparison operator we have learned (after `<`) - Let's see them all in action

1. `===` -  **Identical**. Difference between this and `equal` is, that it also checks type
So this
```php
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 `===`
```php
var_dump((bool) ($a + $b === 30.0));
// bool(false) 
```
We get `false` (or `0` - it's the same too)

2. `!=` - **Not equal**. The opposite of `==` - will return `true` if expressions don't have the same value

```php
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

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

So this:
```php
var_dump((bool) ($a + $b !== 30.0));
// bool(true)
```

Gives us `true`, because the types don't match

4. `<`, `>` - **less than** and **greater than**. I put them together because 
 - We know one of them - it appeared in pt. 3 
 - They are identical to their math equivalent 

```php
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:

5. `>=` - **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 `≥`

```php
var_dump((bool) ($a + $b >= 10)); // bool(true)
// And also
var_dump((bool) ($a + $b >= 30)); // bool(true)
```

6. `<=` - **Less than or equal to**. This one is the opposite of previous one

It's mathematical symbol is `≤`
```php
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](https://www.php.net/manual/en/language.operators.comparison.php) is recommended

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

## Practical Project - Calculator

So, at first start your server and create a new folder - I'll call it `calculator` and inside `index.php`

So, first thing is basic HTML template

```php
<!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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7kafxwdlvoe4p7oiho4v.png)

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.

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

```php
<?php

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

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

And now we could spend a lot of time writing if-else structures, creating really big mess (so-called spaghetti code). But there is another way

**Switch statement**

That's it - there is a structure, that can replace a lot of if-else code and make it clearer

Let's write and analyze it 

```php
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 `$operation`

And then
```php
 case "add": $result = $num1 + $num2; break;
```

This can be represented as 
```php
if($operation == "add"){
   $result = $num1 + $num2;
}
```
And the same is done with each and every `case`

But what does `break` do? This breaks out of the statement

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 `16`, then again `2`, then `0` and in the and 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`  

And what does `default` mean? It means, that if value does not meet any condition, it will get executed

So if somehow `$operations = "idk"`, and as it doesn't match at all, we see `Invalid operation chosen`

(Yes, you have to think about such edge-cases, as sometimes you can get amazed with what can people do with the website. It just has to be as idiot-proof as possible)


Now, let's display the value

In the end add
```php
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?

And that's also why I've created that `result` variable.

So, let's create a **session**

First, at the beginning of each file add 
```php
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
```php
$_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
<?php

?>
``` 

Don't forget the closing here

Now, just display it like normal variable
```php
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?
```php
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
```php
        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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/eb59iky1cs50n3ypzwyf.png)

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](https://github.com/wizarddos/Dev.to-scripts/tree/master/PHP%200%20to%20hero) 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