Lesson 10

Time for some logic!

One of the most important things in programming languages is the logic! This logic allows us to better automate what we intend the computer to do. We will start with one of the most important statements: the IFELSE.

The big: If

The if allow us to verify a condition that we want the computer to test. Example: let’s imagine we have a football shirt and if it’s colour is red we say the owner is a Man United fan…

Now a code example:

Let’s say that we have a variable with a certain value:

So far so good, now, let’s imagine we want the server to show an <h1> if the value is HH otherwise not doing anything. To achieve it we use the if statement:

Confusing? Let’s go item by item: to start the if statement we add if (condition). The condition is the ‘rule’ we want to verify. Everything that is ‘inside’ (between the initial condition and the endif;) is going to be executed. The == is a comparison operator for equal (meaning the left value is equal to the right).

Let’s see our first example implementation:

What happens in this scenario is if the value of the variable \$shirtColor is ‘red’ it will execute the code inside it, in this case it will show and h2 with Manchester United.

If-Else

What happens if our if condition is not ‘true’ and we want to return a different result?

There’s a very common scenario in most of the websites we know that have a very good example of If-Else in place: the login form! Basically the site tests if our password is correct or not, a quick sample of how it would look:

In the example above we are testing if the variable \$password is equal to ‘hacking1’. If it’s true, we show a message saying the user is logged in, if false it executes the else condition: your password is wrong!

Condition Operators

We might want to test different conditions, not only if 2 values are equal, but also if 2 values are different, or if one value is greater than another. These are the most common operators:

 == Equal \$x == \$y Returns true if \$x is equal to \$y != Not equal \$x != \$y Returns true if \$x is not equal to \$y > Greater than \$x > \$y Returns true if \$x is greater than \$y < Less than \$x < \$y Returns true if \$x is less than \$y >= Greater than or equal to \$x >= \$y Returns true if \$x is greater than or equal to \$y <= Less than or equal to \$x <= \$y Returns true if \$x is less than or equal to \$y

Let’s see an example that tests if a value is greater than or equal:

This checks if the variable \$myNumber is greater than 45.

PHP Email

Let’s make our server sending some emails! (please, be aware that our local wamp server doesn’t have an email server, to test, please, send your code to your hackingheroes.org site and try the site there).

The mail function accepts parameters separated by ,(comma):

Another example: