anastasionico

anastasionico.uk

Conditional Structures in PHP

Bee-dee-dee-deep!

Bee-dee-dee-deep!

It’s 8:50 am Monday morning and you’ve just realized that during drowsiness you snoozed the alarm and in about 10 minutes the meeting organized by your project manager, and in which you have to explain how the last functionality that you have pushed into production works, begins.

You wear the first shirt you find, a pair of pants and grab a slice of the pizza that was left yesterday at dinner from the fridge,

Pizza? leftover? really?

Finally,

you take the toothbrush a bit of toothpaste and run to the car, there is no time to waste in front of the mirror this morning.

Vroooooom,

From 0 to 100MPH in less than 1 second, which costs half a tank and the back of the car that is still standing while you are already a hundred miles ahead creating a cartoon effect,

Traffic lights, roundabouts, overtaking, stops, crossroads, drawbridge.

Driving to the limit of survival, you arrive at the office at 9:00 o’clock.

Good Job!

You rush into the meeting room while finish tucking your shirt when your colleagues tell you that the manager took a day off after injuring a fingernail during the regional golf tournament that took place over the last weekend.

The hard life of a web developer!.

Let’s try to learn from what happened,

lesson number 1:
 Do not press the snooze button;

lesson number 2:
 Like when you are driving even in your code there are dozens if not hundreds of decisions to be made.

Learn how to deal with them effectively will make you a better programmer.

Today we will talk about “control structures” and how their use affects the web applications we develop.

These structures,

such as road directions and road intersections indicate the route your car or your web application must follow.

In PHP there are three main types of control structures,

they are conditional structures, loops and namespaces

let’s start with conditional structures!

They are divided into 3 types,

if-elseif-else, switch-case and ternary statement.

About the series

This blog post that belongs to the series “PHP basics for Expert developer”.

If you haven’t already read the other articles

have a look at them 
 PHP basics for expert web developers (1' part)
 Construct and Comments of PHP 7
 How to use variables (PHP 7)
 Composite variable in PHP (Arrays, Object and more)
 PHP operators (part 1)
 PHP Operators (part 2)
 Conditional Structures in PHP

The if statement

Imagine you are facing a crossroads.

A junction gives you the opportunity to choose which way to go, you can go left or right.

Strange to say but in PHP you can also have a fork without bifurcations.

An If statement answers the questions,

what do I do if the condition I indicate is correct?

Is there another option if the condition is false?

What about a third or fourth option?

Let’s pretend you chose to take to cycle rather than drive a car,

Here is an example of if-else statement,

$vehicle = "bicycle"; 
if ($vehicle === "bicycle") {
// take route number 1;
} else {
// take route number 2;
}

The code in question will check the condition since the result is true the first block of code will be executed and the code inside the block else will not be taken into consideration.

I have already explained the meaning of the symbol === a tutorial here

In this type of conditional structure, we can also have multiple conditions.

Let’s say that route number 1 is reserved for bicycles, the second for cars and the third for all types of vehicles.

$vehicle = "car"; 
if ($vehicle === "bicycle") {
// take path number 1;
} elseif ($vehicle === "car") {
// take path number 2;
} else {
// take path number 3;
}

In the above example, our code will check the first condition, understand that the result is false and will go on and check the second one which will be true and will be executed.

If it were to be false, it would have passed the second as well and the code inside the else would have been executed.

As I said,

in PHP we can also have coding without an alternative.

$vehicle = "boat"; 
if ($vehicle === "plane") {
// take path number 1;
}

In this case, the code bypasses the entire code block inside the statement.

While I was researching about the content of this article, I come across a blog post written by Nick Galbreath, CTO and co-founder of Signal Sciences, that I found very interesting,

The post describes the pros and cons of using naked code blocks (for naked I mean blocks without being circumscribed by braces) on if statement.

Here is the link: Never Use Naked If Statements

The if statement is a very useful feature of the language but there is a better alternative in case we are dealing with 3 or more alternatives.

This alternative is called switch-case.

The switch statement

Switch operators work much like the if operators.

But there are some small differences between them, both in syntax and in rules that must be followed.

The main purpose of the switch operator is to make more declarations available to the web developer by using a cleaner code.

Using a switch instead of a series of if-elseif-also we can still check multiple conditions and give more options to the code depending on their result.

Here is an example of switch keeping the previous codes:

switch ($vehicle) { 
case 'bicycle':
// take path number 1;
Break;
case 'car':
// take path number 2;
break;
case 'motorbike':
// take path number 3;
break;
case 'airplane':
// take path number 4;
break;
case 'boat':
// take path number 5;
Break;
}

How clean and easy to read is that?

As you may have noticed both if statements and switch declarations have practically the same function,

That is to control the flow of your code based on the value of the variable we have to check.

Now,

As I said, although the function of these two statements is the same.

There are several rules that must be respected if you do not want to encounter errors during the execution of the code.

Did you notice that at the end of each block there is a break command?

let’s try to understand how the switch statement works and what happens behind the scenes.

The switch declaration checks each “case” starting from the first one and descending one at a time.

Once a condition is true the flow enters and executes the block of relevant code (keep this sentence in mind).

Once all the code has been executed, there are 2 options:

Finish the block,

End the switch declaration and continue with the following command (which is what we want in 99% of cases) or

Continue with the next case (this happens because, as I said, we have already passed the condition, so we are already inside the switch).

What you need to do to prevent your code from performing operations that you do not want it to perform is to stop the execution.

You do this through the break command.

The “break” command interrupts the current execution, usually loops (foreach, while and do-while) in this example switch, and changes the flow structure.

Not many web developers know, and for this reason, it is not so much in use that the break command accepts an argument.

It is an optional and numerical value and indicates how many nested structures must be interrupted.

Still following the previous example, think of a switch statement within another switch statement.

The default value of the break command is 1, which indicates that only the immediate structure is interrupted.

Bonus Section:

If you are a fairly advanced web developer, there are chances that you know what it is or at least you have already heard of routing.

It is the practice to route the HTTP request to different pages of your web application.

It is very useful when you want to create easy-to-remember and SEO friendly URLs.

In the link below, Tania Rascia, a web developer and designer from Chicago, takes advantage of the switch operator to redirect the user via the global variable $_SERVER [‘REDIRECT_URL’].

The article is very short and incredibly explanatory.

Check The Simplest PHP Router out!.

The ternary operator

You have already seen the ternary operator a couple of episodes of this series ago.

Into specific when I wrote about the various operators available for those who want to start programming using PHP (Logic operator section).

Now it’s time to go a little more in detail about this conditional operator.

The idea of using the ternary operator is very old, in fact, goes back to the programming language C, one of the fathers of all languages.

The ternary operator is nothing more than an if statement, which can be written in a single line, basically is an if else shorthand.

Here is an example:

echo (isset($var))? "the variable is set": "the variable is not set";

The ternary operator returns a value, which in the previous case has been echoed out on the screen but can also be saved into a variable to be used later.

Personally,

I really like to use it and, for short statements that require only one line and/or conditions that need to give me back a variable, the ternary operator is the real deal.

Not to mention how simple it makes reading the code,

both when I have to read and try to understand the code of others, and, more important when others have to read and understand the code I have written.

As I am sure for many of you, since my first blocks of PHP I have always been in front of the screen for hours and hours.

I loved to do practice and still remember the excitement in learning new functions and new techniques.

In the early stages,

I had not yet understood that all these new information only create mental clutter if not used on a clean and ordered code.

I am a supporter of writing clean code, and a firm opponent of mental cluttering.

especially during long hours of daily programming.

(let me know if you’d like to read about this topic in another blog post).

For this reason,

I recommend that, once you understand how it works and when it is best to use it, make use of the ternary operator as much as possible.

Conclusion

Conditional structures are fundamental parts of every programming language.

Learning them, learning syntax, understanding when to use one instead of others is a must.

Fortunately PHP gives us a wide choice and uses a very simple syntax to understand and reproduce them,

Usually,

you will not make any mistakes after only a couple of times you have written the statements.

In this post,

you saw that the code can take different paths and that you as a web developer are in control of the flow of your code and what users of your program will do.

Conditional structures are a simple topic, like everything written in this series.

And, even if there are small correlated details that require a little effort to be fully understood (see command break),

In general,

you can take advantage of their full potential right away.

I hope this post was clear and in some degree, fun.

In the next episode you will get to take a look at another fundamental part of the PHP language that belongs to the category of control structures:

The loops.

What’s better than starting to practice your new knowledge?
Start doing it now!

Take advantage of the power and the speed of Blue Host and create an account where you can exercise and see your improvement on a live server at less than a Starbuck’s Caffe Mocha per month.

Originally published at anastasionico.uk.

More by anastasionico

Topics of interest

More Related Stories