Control Structures - LEARN PHP IN A DAY: The Ultimate Crash Course to Learning the Basics of PHP in No Time (2015)

LEARN PHP IN A DAY: The Ultimate Crash Course to Learning the Basics of PHP in No Time (2015)

Chapter 4. Control Structures

Introduction

PHP scripts are built out of a series of statements. A statement can be an assignment, a function call, a loop, a conditional statement or even empty statements. Statements can be grouped into statement groups by encapsulating them with curly braces. A statement group is considered a statement itself.

In this chapter we will observe the behavior of different types of statements.

If statements

If Statements

The “if” statement is one of the most important structures inside any language.This control structure allows you to have conditional execution of code fragments. PHP’s “if” structure is similar to that of C. That is, each if statement at its most basic looks likeif (expression) statement. The expression is evaluated to its Boolean value. If the expression is TRUE, PHP will execute the statement. If it is FALSE, it will not execute it. A simple example is:

Very often you would need to execute more than one statement if a certain condition is true. You don’t need to wrap each statement in its own if clause. Instead, you can use curly braces to wrap the code you want to be executed conditionally.

You can even take it one step further and nest if statements inside of other if statements.

If Else Statements

In some cases you want to execute a piece of code when a condition is met and a different piece of code if that condition is not met. In that case, you would have to use andif-elsestatement.else extends an if statement to execute an expression if the statement evaluates to FALSE. Here is an example that extends the one above:

If-else if-else statement

This is yet another modification to theifstatement and it presents the most generalized form of an if statement. It includes andifstatement that executes a block of code if the statement if TRUE. After thisifstatement, you have a number ofelseif statements. Each else if statement has a condition associated with it and a block of code to be executed if true. The block of code is executed only if the condition evaluates to true. After all of theelseifstatements there is a closingelsestatement. You can think of this as a kind of default case. If none of the conditions evaluate to true, theelse statement will be executed. Here is an example:

Keep in mind that as soon as a condition is evaluated to TRUE, the script executes the associated block of code and breaks out of the if-elseif-else structure and will not go down to any of the other conditions. That is, only one condition will be executed when using an if-elseif-else.A structure that is related to the if-elseif-else structure is theswitch statement which is the subject of discussion next.

Switch

The switch statement is similar to a bunch ofif statements operating on the same variable. Imagine you have some variable that can take some values. In your code, you want to compare if that variable corresponds to some specific values. For each value, there is a code segment that has to be executed. Also, if the variable does not meet any of those cases, you want to execute some default piece of code. You could do this using a long if-elseif-else structure, but you could also do it using aswitch statement.

A switch statement does the same thing as an if-else-if structure, but saves you some typing. The syntax for a switch statement is:

You can have as many cases as you need for your code. An important thing to keep in mind is the presence of thebreakstatement. Thebreakcommand breaks you out of the current structure or loop you are in. If you did not have the break command inside each case, PHP would go through each case. That is, PHP checks the variable against each case and executes the specified code within if the comparison returns TRUE. If PHP does not encounter abreak command, it continues to the next case and executes the specific code if the comparison of that case returns TRUE.This is one of the differences between using anif-elseif-elsestructure and aswitch statement.

Let’s take a look at an example comparison between theif-elseif-elsestructure and theswitch statement:

That’s pretty much all there is to switch statements. Learn how to utilize them and you will make your life faster than having to write out all of the if-else statements.

Alternate syntax to control structures

Before going on to each of the other control structures, let’s take a moment to go to over the alternate syntax that PHP offers us for control structures. PHP offers us an alternative syntax for some of the control structures. These are:if,while,for,foreachandswtich. In each case, the basic form of the alternate syntax is to change the opening brace to a colon and the closing brace to anendif;,endwhile;,endfor;,endforeach;, orendswitch;, respectively (basically end with the name of the control structure appended.). What this allows us to do is break out of PHP in order to include for HTML, for example.

We haven’t really talked much about including HTML inside of your PHP scripts, but it is actually a really easy concept. One way to include the HTML is to save the HTML string to a variable and thenechoorprint that variable. In fact, this is a method that you are going to find yourself using quite often. This method, however, has its shortcomings. For example, imagine you want to create a table that is not dynamically generated (that is, you are not using PHP to generate the table rows for you). The table has a specific layout and you want to include the value of some PHP variable inside one of the cells for example. If you try to write that inside a variable, you will find that it is very tedious and not efficient. (Unless for some reason you need to store that HTML in a variable, in that case you are stuck using the HTML to variable method). You can break out of PHP and then break back into PHP and include the necessary HTML inside the break. Here is a simple example:

OK, after that digression, let’s see the alternate syntax for an if statement:

This looks exactly like the code above and will work exactly as you would expect it to.

Helpful Tip!

Whenever you are creating control structures that have to be encapsulated inside of curly braces, always write out the entire control structure skeleton first before going in to fill it up. That is, if you are creating an if statement, you would write out:

Always make sure you do this! If you do this, you will never have to keep track of opening and closing brackets and/or parentheses. In fact, you should make it a rule to yourself. WHENEVER YOU OPEN A BRACKET OR PARENTHESIS, CLOSE IT BEFORE YOU WRITE ANY OTHER CODE. Then go back and fill in the code you need. This will keep you from making stupid errors and spending precious time debugging code while you could have been writing an amazing application.

Another way to write the alternate syntax is to keep the curly braces and break out of PHP like normal. The following two statements are equivalent:

That does it for the alternate syntax for control structures. You will often find yourself these alternate syntaxes in your code when you are juggling between PHP and HTML. In the next subchapter we will begin out discussion of the different types of looping structures in PHP. Keep in mind that the alternate syntax we discussed in this structure is applicable to some of the next structures as well.

While

This is the first type of loop that we will be talking about and it is also the simplest. The form of a while statement is:

The meaning of the while loop is also simple to understand. While loops tell PHP to execute the nested statement (does not need to be a single statement, it could be a block of code and in most cases it will be) as long as the while expression evaluates to TRUE. The expression is evaluated once at the beginning of the loop so even if the value of the expression is to change during the execution of the loop, the execution of the loop does not terminate (unless told otherwise) until the beginning of the next iteration. It is important to note that if the expression is FALSE the first time PHP checks it, the statement will not be executed.

As we mentioned, the statement could be a number of statements wrapped inside of curly braces. As with the if statement, we can use the alternate syntax to form our while loop. This is the general form of a while loop using alternate syntax for control structures:

Let’s run a simple example of this loop to count from 1 to 10.

While loops are very commonly used, especially when you are extracting information from a database (we’ll look at that in a later chapter).

One potential pitfall to lookout for is creating infinite loops, that is, loops that will never terminate (the while condition will always evaluate to TRUE). There are cases in which you would want to create an infinite loop and terminate it on a certain condition, but other times this behavior is not desired. Imagine the following examples.

You want to set up an application that will check the status of something and send an email to a user. Say, you are monitoring the status of a server and you want to know if something is going wrong. You want a script that will be running indefinitely and checking the server status at defined intervals. This can be achieved using an infinite loop that pauses for some defined amount of time before it resumes operation. Another example is if you are setting up a simple game using PHP to test your skills. You want to set up a main loop (you can refer to it as a “game loop” if you wish) that will run once each frame and do the operations that are associated with the game. Another example is if you are waiting for user-defined input. In that case you would set up an infinite loop that takes the user input and operates on it.

At the start infinite loops can be tricky and can cause you some problems, so try to avoid them until you are comfortable with the concept of looping and know what you are doing.

The easiest way to set up an infinite loop is:

The while condition will always evaluate to TRUE (in essence, the loop reads:while TRUE, execute {statement}).

Do-while

The do-while loop is similar to the loop we saw in the previous subchapter, with a minor difference. Do-while loops have the following structure:

This means that PHP will execute everything that is inside the do clause first, and then it will check the condition. If it evaluates to TRUE, PHP will loop back. What you will notice is that you evaluate the condition at the end of the loop instead of the beginning. This means that the code inside the do statement is guaranteed to run at least once. For example:

This code will execute exactly one time before terminating because the truth expression evaluates to FALSE.

The only major difference between a do-while and a while loop is that the do-while will run the code at least once, whereas the while loop will not. With that being said, it should be noted that the while loop is the loop that you will be using most commonly in practice, but don’t forget that the do-while loop exists!

For

For loops are more complex than while and do-while loops, but you should become really comfortable with them because you will be using them all the time! Here is the basic syntax of a for loop:

The first expression is evaluated (executed) once at the beginning of the loop.

The second expression is evaluated at the beginning of each iteration. If it evaluates to the TRUE, the loop will continue, and the nested statement(s) are executed. If it evaluates to FALSE, the execution of the loop terminates. At the end of each iteration, the third expression is evaluated (executed).

Each of the expression can be empty or it can contain multiple expressions separated by commas. If the second expression is empty, PHP assumes it to be TRUE. Essentially this will create an infinite FOR loop. Let’s look at the following examples:

As with the while and if statements, for loops support the alternate colon syntax for control structures:

Very often, people will loop through arrays using for loops. While it is not wrong to do this, it is more convenient to use foreach loops for arrays or objects, because that control structure is specifically setup for arrays and provides you with more control.

Now that we’ve introduced the two types of looping in PHP, you may be asking yourself: What is the difference between a while and a for loop and when should you use each one? Here is the general rules of thumb that will guide you through the proper usage of for and while loops in your PHP applications.

For loops are for when you know how many iterations of the loop you need. For example, if you want to operate on each element of an array, you use a for loop that loops from the first to the last value of the array. The easiest way is if you have an array where each key is an incremental number. You initialize the counter variable to 0 (this is usually going to be the first value of the array. Remember, PHP counts from 0). After that, you check whether you have reached the last element of the array. To do that you check whether the counter variable is smaller than or equal to the length of the array (you can use thecount() function to find the number of elements in the array.) The last expression will be incrementing the counter variable.

While loops on the other hand, are to be used when you don’t know how many iterations your loop will take until the truth condition evaluates to FALSE.

A closing word about for loops:

For loops can be used on string characters as well. Can you set up a for loop that will print out the letters of the alphabet?

Foreach

The foreach construct provides an easy way to iterate over arrays and objects, but it will only work on arrays and objects and will give you an error if you try to use a foreach on a different kind of variable type. There are two syntaxes to the foreach loop:

The first syntax loops over an array (array_expression)and takes the value of each element and assigns it to$value. In the second syntax, you reference both the key and the value of each element of the array. Let’s look at an example:

Note that the reference to$value remains after the foreach loop, so you should unset it (destroy it) after the loop to prevent any issues with your code.

Foreach loops and while loops are very commonly used in tandem when working with database information, but we shall see that in the chapter concerning databases.

Break

So far we have seen the use of thebreak command to break out of loops, but we have not defined it explicitly until now.

break ends execution of the current for, foreach, while, do-while or switch structure.

break accepts an optional numeric argument which tells it how many nested enclosing structures are to be broken out of.

Here is an example of how thebreak command works with the optional argument:

Continue

The continue command is similar to the break command, but it does not break out of the loop. Instead it continues to the next iteration of the loop. This command can be used inside of switch statements as well, but the results of that would be the same using a break. You can think of it this way:

Continue takes you to just before the last closing curly bracket of your structure. If it is a loop, you will go to the next iteration of the loop. For a switch statement, when the execution is taken to just before the closing curly bracket, you are essentially being taken to the end of the switch statement.

In contrast, break will take you to just outside the last closing curly bracket of your code. For a loop that means that you have broken out of the loop. For a switch statement, that means that you break out of the switch statement and do not go through any of the cases.

As with the break statement, continue takes an optional argument that tells PHP how many levels of enclosing loops it should skip.

Return

The return command returns program control to the calling module. Execution resumes at the statement following the called module’s invocation.

If you use return from within a function, the return statement immediately ends execution of the current function, and returns the argument of the return as the value of the function call.

Try to abstain from using return inside of a file that is included in another file as this is bad practice.

Include

Files are included based on the file path given or, if none is given, the include_path specified. If the file isn't found in the include_path, include will finally check in the calling script's own directory and the current working directory before failing. The include construct will emit a warning if it cannot find a file; this is different behavior from require, which will emit a fatal error.

If a path is defined — whether absolute (starting with a drive letter or \ on Windows, or / on Unix/Linux systems) or relative to the current directory (starting with . or ..) — the include_path will be ignored altogether. For example, if a filename begins with ../, the parser will look in the parent directory to find the requested file.

For more information on how PHP handles including files and the include path, see the documentation for include_path.

When a file is included, the code it contains inherits the variable scope of the line on which the include occurs. Any variables available at that line in the calling file will be available within the called file, from that point forward. However, all functions and classes defined in the included file have the global scope.

Require

Require is identical to include, except that upon failure, it will return an error and execution of the script will stop.

Require_once

This is similar to require, except require_once will check whether the file has been included up to that point. If it has, it will not include it again. Hence, it will require the file to be included only once.

Include_once

Works exactly like require_once, except it will not produce an error.

Conclusion

This is probably one of the most important chapters in the book. With the concepts and techniques you learned in this chapter you should be able to fully utilize your PHP skills to create amazing applications. The control structures introduced here are the basis of each PHP script you will write and encounter. Combine these with the next chapters about functions and database connections and usage and you will be well on your way to creating advanced and complicated web applications.

Exercise 1

In this PHP exercise, you will use a conditional statement to determine what gets printed to the browser. Write a script that gets the current month and prints one of the following responses, depending on whether it's August or not:

It's August, so it's really hot.

Not August, so at least not in the peak of the heat.

Hint: the function to get the current month is 'date('F', time())' for the month's full name.

Exercise 2

In this PHP exercise, you will put all the loops through their paces. Write a script that will print the following to the browser:

abc abc abc abc abc abc abc abc abc

xyz xyz xyz xyz xyz xyz xyz xyz xyz

1 2 3 4 5 6 7 8 9

1. Item A

2. Item B

3. Item C

4. Item D

5. Item E

6. Item F

Create the 'abc' row with a while loop, the 'xyz' row with a do-while loop, and the last two sections with for loops. Remember to include HTML and source code line breaks in your output. No arrays allowed in this solution.

Exercise 3

Loops are very useful in creating lists and tables. In this PHP exercise, you will use a loop to create a list of equations for squares.

Using a for loop, write a script that will send to the browser a list of squares for the numbers 1-12.

Use the format, "1 * 1 = 1", and be sure to include code to print each formula on a different line.