DEV Community

Mateusz Jasiński
Mateusz Jasiński

Posted on • Updated on

PHP 0 to hero pt.5 - Math and Sessions in PHP

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

$a = 25;
$b = 5;
Enter fullscreen mode Exit fullscreen mode

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

$c = -4.5;
Enter fullscreen mode Exit fullscreen mode

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

echo $a + $b;
// 30
Enter fullscreen mode Exit fullscreen mode

+ 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:

echo $a - $b;
// 20
Enter fullscreen mode Exit fullscreen mode

Multiplying:

echo $a * $b;
// 125
Enter fullscreen mode Exit fullscreen mode

Division:

echo $a / $b;
// 5
Enter fullscreen mode Exit fullscreen mode

And last operation - modulo

echo $a % $b;
Enter fullscreen mode Exit fullscreen mode

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
echo 5 ** 2;
// 25
Enter fullscreen mode Exit fullscreen mode
  1. Using pow() funtction
echo pow(5, 2);
// 25
Enter fullscreen mode Exit fullscreen mode

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

echo sqrt($a);
// 5
Enter fullscreen mode Exit fullscreen mode

But what if we want get other root than square one - let's use old trick we have learned in high school

echo pow(8, 1/3);
// 2
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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) 
Enter fullscreen mode Exit fullscreen mode

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
var_dump((bool) ($a + $b == 30.0));
// bool(true)
Enter fullscreen mode Exit fullscreen mode

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) 
Enter fullscreen mode Exit fullscreen mode

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

  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)
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

Gives us true, because the types don't match

  1. <, > - 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
var_dump((bool) ($a + $b > 10.0));
// bool(true) 
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode
  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)
Enter fullscreen mode Exit fullscreen mode

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

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

<!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>
Enter fullscreen mode Exit fullscreen mode

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.

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

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

$num1 = $_GET['num1'];
$num2 = $_GET['num2'];
$operation = $_GET['operation'];
$result = 0;
Enter fullscreen mode Exit fullscreen mode

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

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;
}
Enter fullscreen mode Exit fullscreen mode

So, step by step

inside brackets switch takes a value which will then be compared - here $operation

And then

 case "add": $result = $num1 + $num2; break;
Enter fullscreen mode Exit fullscreen mode

This can be represented as

if($operation == "add"){
   $result = $num1 + $num2;
}
Enter fullscreen mode Exit fullscreen mode

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

echo $result;
Enter fullscreen mode Exit fullscreen mode

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

session_start();
Enter fullscreen mode Exit fullscreen mode

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");
Enter fullscreen mode Exit fullscreen mode

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

<?php

?>
Enter fullscreen mode Exit fullscreen mode

Don't forget the closing here

Now, just display it like normal variable

echo $_SESSION['result'];
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

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();
        }
Enter fullscreen mode Exit fullscreen mode

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

Top comments (0)