|

PHP Flow Control Statements

9 Awesome Hacks to Get Your Flow On In PHP

It’s time to get with the program friends – we need to Go With The Flow. In this episode of our PHP Tutorial Series we’ll be taking a closer look at all of the Flow Control Statements available to us. When we’re working with these control statements, we’ll be evaluating variables and expressions for a boolean value and then taking action based on a true or false state. Aren’t you so glad we just covered booleans now?! In any event we have a lot to cover, we’ll look at if, elseif, ternary, switch, while, for, foreach, try catch, and return. Let’s jump into working with the various flow control statements we have in PHP!


1. if

The workhorse of creating basic conditional logic in your programs is the trusty if statement. We use the if statement to check the boolean value of a variable or expression contained within a pair of parenthesis. The expression is checked, and if it is true, the statement will run. No doubt you have seen this before, but let’s look at the structure of this statement here.

Just as useful is the ability to specify some other statement to run should the expression being evaluated be false. We can do that with this structure.

There are opinions abound on the use of the curly braces. If you were to omit them, the code would still run. There is a fair chance however that the code readability police will hunt you down and place you under arrest for sloppy coding. The take away, use your curly braces! If you really have a thing against the curly braces, you could use this alternative syntax as well.

This approach sometimes works if there are large amounts of html in the file you happen to be working with. You might see this type of syntax in a view file for instance in a model view controller type application. You can also nest if statements to get the behavior you want.

You can use the above style all you like. If you want to use yet another syntax for the same effect, you can do that as well. This would be by combining the else and if into one elseif. This approach is not mandatory, in fact some would say the first approach is a bit more readable. We’ll show how to use this additional syntax however for completeness.

As they say in Hollywood, whatever blows your hair back friend.


2. ? :

You may be wondering, whats up with the question mark colon in large font? This is the ever useful ternary operator, and you can think of it as a shorthand expression of a simply if statement. It’s a handy syntax that isn’t used as much as you’d think it would be. With the ternary operator, the expression is first evaluated. Then, if that expression is true, statement1 will run. If the expression is false, statement2 runs. The syntax is shorter, but contrary to the if statement, it is sometimes not clear exactly what the intended effect was meant to be when reading the code at a later time. This is the syntax if you would like to use it.


3. switch

Now we move on to the switch statement. When would we want to use the switch statement? The switch statement is good when a variable could have one of several values, and each value would have a different operation associated with it. A good example might be a variable of $day. Consider there are seven days in the week, and depending on the day of the week, your program would take a different action for each scenario. This is how the syntax looks.

There might be a scenario where you want the same action to take place for several different states of the variable being tested. Maybe you’d like to start celebrating the weekend on Wednesday, Thursday, and Friday. You can do just that with a fall through like this.


4. while

Moving on in our control flow adventures brings us to the while loop. This is the first loop we have taken a look at. The format follows this format.

That looks an awful lot like an if statement you might be thinking. In fact you are right, the only difference is that the if is now a while. The way this works is expression is evaluated and if it is true, the statement runs. The expression then gets evaluated again, and if still true, the statement runs again. This happens at lightning quick speed, and you can complete hundreds of statement executions very quickly. The statement will usually have an ability increment the expression so that the loop does not run forever. If it did not have this ability, the loop might continue to infinity and the world would end program would crash. Let’s count by tens to 100 with a while loop.

10
20
30
40
50
60
70
80
90
100

Easy Peasy Lemon Squeesy, People. One other thing you might like to do with your loops is to be able to filter within them and break out of them if needed. You can do this by placing an if inside the loop and a break inside the loop respectively. Let’s check each number to see if it is evenly divisible by 3 and output a message indicating so if this is the case. Let’s also break out of the loop at 80.

10 is not divisible by 3
20 is not divisible by 3
30 is divisible by 3
40 is not divisible by 3
50 is not divisible by 3
60 is divisible by 3
70 is not divisible by 3
80 is not divisible by 3

Smashing! That was awesome stuff.


5. do while

You could rewrite the prior example with a do while loop. The difference with a do while loop is that since the while condition comes after the actual statement code, the loop will always run at least a minimum of one time no matter what. With the standard while loop, there is a chance that the loop will never run at all, since if the expression is false, the loop won’t run! You’ll have to explore your use case, but it’s safe to say that do while loops are far less common than while and the other types of loops. This is how to write one if you like though.


6. for

The for loop is really the workhorse of looping constructs. It’s a little more clean than the while loop since it builds the counter right into the expression. No need to have an iterator in the statement body of the loop with this scenario. We can rewrite our little counting program with a for loop just like this. Note that the filtering and break mechanisms work just as well in for loops as they did with while loops. In fact, let’s do the same program but count by 100’s this time and break the loop at 700. Observe.

100 is not divisible by 3
200 is not divisible by 3
300 is divisible by 3
400 is not divisible by 3
500 is not divisible by 3
600 is divisible by 3
700 is not divisible by 3

Oh man, that is Cool and The Gang!


7. foreach

We talked a lot about arrays in this PHP Tutorial Series. We even came up with an Epic PHP Array Functions List to keep as a reference. The time has come now, for us to iterate over arrays. We will do this with the always useful foreach construct. Sometimes you’ll just want the values, and other times you might like to get the keys and the values. There are also a couple of ways to create the loop, so in total you have four options for the syntax.

Now let’s put our foreach skills into action. Let’s say we have an array of stocks and we want to process each one of them in turn. We’ll take an array of ticker symbols that are in all lowercase. We’ll then place a function inside the loop of our foreach construct, and each time the loop runs, and new lowercase ticker symbol will be fed into our strtoupper function. We’ll simply echo this process out to the browser to see it in action.

MSFT
GOOG
AAPL
ADBE
CSCO
JNPR
GPRO
NFLX

Now we want to be able to process not only the ticker symbol, but the name of the company each ticker symbol is associated with. We can do this using the key value pair syntax of our foreach loop. Check it out.

The stock ticker for Microsoft is MSFT
The stock ticker for Google is GOOG
The stock ticker for Apple is AAPL
The stock ticker for Adobe is ADBE
The stock ticker for Cisco is CSCO
The stock ticker for Juniper is JNPR
The stock ticker for Go Pro is GPRO
The stock ticker for Netflix is NFLX

So you can see that by using the foreach construct we can quickly get access to indices, keys, and values in both standard index based arrays as well as associative arrays.


8. try catch

We all know that computers and the software that run them are 100% fail proof, error free, and work perfectly at all times. If you believe that last sentence, there is a bridge in Brooklyn you may consider buying 🙂 Actually, the try catch construct is available to us for the very fact that sometimes things can and will go wrong with our software. The try catch gives us the ability to try something out, and if things don’t go as planned we have a contingency plan to handle any problems. A perfect example is connecting to a database. There are several things that could go wrong. To deal with this, just put your code in a try catch block like so.

We are ready to work with the database!

If something went wrong, like the database not being found, we get an error.

Whoops! That was an error: SQLSTATE[HY000] [1049] Unknown database ‘verge’

Script ended unexpectedly.


9. return

The return statement is used so much we don’t even think of it many times. It just exists happily in our code, returning values or control to the calling code going about it’s business. Usually we’ll see return being used in a function something like this.

12

In this code we create a user defined function that returns a value. You can see when we call that function by simply writing it’s name and passing in two variables, it assigns or returns the sum into the variable $result. We are then free to echo out that value to the screen. Pretty Slick!